congr / world

2 stars 1 forks source link

LeetCode : 325. Maximum Size Subarray Sum Equals k #474

Closed congr closed 5 years ago

congr commented 5 years ago

https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/

image

congr commented 5 years ago

What kind of person can solve this with O(N)?

congr commented 5 years ago
class Solution {
    public int maxSubArrayLen(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap();
        int sum = 0, max = 0;

        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));
            } 

            map.putIfAbsent(sum, i);
        }

        return max;
    }
}