美文网首页
[LeetCode 325] Maximum Size Suba

[LeetCode 325] Maximum Size Suba

作者: 灰睛眼蓝 | 来源:发表于2019-08-06 16:22 被阅读0次

    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:

    Input: nums = [1, -1, 5, -2, 3], k = 3
    Output: 4 
    Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.
    

    Example 2:

    Input: nums = [-2, -1, 2, 1], k = 1
    Output: 2 
    Explanation: The subarray [-1, 2] sums to 1 and is the longest.
    

    Follow Up:

    • Can you do it in O(n) time?

    Solution: 思路与#560一致,用prefixSum array 和 hashtable来做

    class Solution {
        public int maxSubArrayLen(int[] nums, int k) {
            if (nums == null || nums.length == 0)
                return 0;
            
            // construct prefixSum
    //         int[] prefixSum = new int[nums.length + 1];
    //         int prefix = 0;
    //         int index = 1;
            
    //         for (int num : nums) {
    //             prefix += num;
    //             prefixSum[index ++] = prefix;
    //         }
            
            //for each j, in prefixSum array, find the maxisum size subarray sum equals k
            // sum of subarray (i, j) = prefixSum [j] - prefixSum[i]
            Map<Integer, Integer> prefixSumVsIndex = new HashMap<> ();
            prefixSumVsIndex.put (0, -1);
                
            int maxSize = 0;
            int prefixSum = 0;
            
            for (int j = 0; j < nums.length; j++) {
                prefixSum += nums[j];
                
                if (prefixSumVsIndex.containsKey (prefixSum - k)) {
                    int prefixIndex = prefixSumVsIndex.get (prefixSum - k);
                    maxSize = Math.max (maxSize, j - prefixIndex);
                }
                
                // 只需记录第一个出现的prefixSum的index,因为是从左向右遍历,往后的index肯定更大,不可能是max的
                if (!prefixSumVsIndex.containsKey (prefixSum)) {
                    prefixSumVsIndex.put (prefixSum, j);
                }
            }
            
            return maxSize;
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode 325] Maximum Size Suba

          本文链接:https://www.haomeiwen.com/subject/fhdwdctx.html