1477. Find Two Non-overlapping Sub-arrays Each With Target Sum

T: O(n)

S: O(n)

class Solution {
    public int minSumOfLengths(int[] arr, int target) {
        int n = arr.length;
        
        int sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        
        int best = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            sum += arr[i];
            if (map.containsKey(sum - target)) {
                len = Math.min(len, i - map.get(sum - target));
            }
            
            // 左邊一定會先出來, 所以 len != Integer.MAX_VALUE, 不然空有右邊一個, 沒有用
            if (map.containsKey(sum + target) && len != Integer.MAX_VALUE) {
                res = Math.min(res, len + map.get(sum + target) - i);
            }
        }
        return res == Integer.MAX_VALUE ? -1 : res;
    }

}

/*
0 -1. => 0 -(-1) = 1
3 0
5 1
7 2
11 3  map.get(curSum + target) = get(11+3) = get(14) = 4, 4-i = 4-3 = 1
14 4
            3
    [3,2,2, 4, 3]  target = 3
  0  3 5 7 11 14  
               4
  
         cursum      |
  |--------|---------|--------|
    pre        target  target
    
思路: 預先建構出 presum hashmap

之後 check map.get(sum - target), i - map.get(sum - target)
    
          map.get(sum + target), map.get(sum + target) - i
          
          這樣不會 overlap, 因為當 for (int i = 0; i < n; i++)
          
          我們總是去看 i 之前的, 也就是 sum - target 有沒有 符合的
          和看 i 之後的, 也就是 sum + target 
*/

if arrays contain negative number

T: O(n)

S: O(n)

Last updated

Was this helpful?