[LeetCode] 325. Maximum Size Subarray Sum Equals k

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.
Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Given nums = [1, -1, 5, -2, 3]k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)
Example 2:
Given nums = [-2, -1, 2, 1]k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?

Thought process:
Get the prefix sums of the array. Then iterate the prefix sums using a decrementing length variable.

Solution 1 (Brute force):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        if (nums.length == 0) {
            return 0;
        }
        
        int[] prefixSum = new int[nums.length + 1];
        for (int i = 1; i <= nums.length; i++) {
            prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
        }
        
        for (int i = nums.length; i >= 0; i--) {
            for (int j = prefixSum.length - 1; j - i >= 0; j--) {
                if (prefixSum[j] - prefixSum[j - i] == k) {
                    return i;
                }
            }
        }
        
        return 0;
    }
}

Time complexity: O(n^2).

Follow-up:
Iterate through the array. Calculate prefix sums as I iterate. Use a hash map to keep track of prefix sum -> index. For each prefix sum, check if map contains a key that equals prefix sum - k. If so, the length of the sub-array is index - map.get(prefixSum - k). Put current prefix sum -> index into the map only if prefix sum doesn't exist in the map yet. Initialize the hash map with an entry 0 -> -1.
Further thoughts: because I'm not using all of the prefix sums, I only need a variable to keep track of the previous sum.

Solution 2 (Hash table):
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        int max = 0;
        int sum = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (map.containsKey(sum - k)) {
                max = Math.max(max, i - map.get(sum - k));
            }
            if (!map.containsKey(sum)) {
                map.put(sum, i);
            }
        }
        return max;
    }
}

Time complexity: O(n).

Comments

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula