LeetCode325 Maximum size subarray sum equals K(Not Really Understand)
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.
this is a really easy undetstanding problem. and the follow up is do it in O(n) time.
public class Solution {
public int maxSubArrayLen(int[] nums, int k) {
Map<Integer, Integer> hm = new HashMap<>(); //use nums[i] as key and its index as value
int result = 0, sum = 0;
hm.put(0, -1);
for(int i = 0; i < nums.length; i++) {
sum += nums[i]; //
if (hm.containsKey(sum - k)) result = Math.max(i - hm.get(sum - k), result); //results always gets the maximum length so far
if (!hm.containsKey(sum)) hm.put(sum, i); //if we don;t have current sum as the key, we create one
} //so this for statement constrauct the hashmap while check the longest subarray?
return result;
}
}

浙公网安备 33010602011771号