Leetcode:maximum Size subarray Sum Equals k

Source: Internet
Author: User

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.  1= [1,-1, 5,-2, 3], k = 3,return 4. (Because the Subarray [1,-1, 5,-2] sums to 32= [-2,-1, 2, 1], k = 1,return 2. (Because the Subarray [-1, 2] sums to 1 does it in O (n) time?

Like the other subarray sum problems lintcode:subarray sum closest

Use a HashMap to keep track of the sum from index 0 to index I, use it as the key, and use the current index as the value

Build the Hashmap:scan from left to write, if the current sum does not exist in the HashMap, put it in. If The current sum is does exist in Hashmap, does not replace or add to the older value, simply does not update. Because This value might is the left index of our Subarray in later comparison. We is looking for the longest subarray so we want the left index to be the smaller the better.

Every time we read a number in the array, we check to see if Map.containskey (num-k), if yes, try to update the MaxLen.

1  Public classSolution {2      Public intMaxsubarraylen (int[] Nums,intk) {3         if(nums==NULL|| nums.length==0)return0;4Hashmap<integer, integer> map =NewHashmap<integer, integer>();5Map.put (0,-1);6         intsum = 0;7         intMaxLen =Integer.min_value;8          for(inti=0; i<nums.length; i++) {9Sum + =Nums[i];Ten             if(!map.containskey (sum)) { One map.put (sum, i); A             } -             if(Map.containskey (sum-k)) { -                 intindex = Map.get (sum-k); theMaxLen = Math.max (MaxLen, I-index); -             } -         } -         returnMaxlen==integer.min_value? 0: MaxLen; +     } -}

Leetcode:maximum Size subarray Sum Equals k

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.