[Leetcode] Maximum Size subarray Sum Equals K maximum sub-array sum of 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.

Example 1:

Given nums = [1, -1, 5, -2, 3] , k = 3 ,
Return 4 . (Because the Subarray sums to 3 and is the [1, -1, 5, -2] longest)

Example 2:

Given nums = [-2, -1, 2, 1] , k = 1 ,
Return 2 . (Because the Subarray sums to 1 and is the [-1, 2] longest)

Follow up:
Can do it in O (n) time?

This problem gives us a one-dimensional array nums, let us sum to K maximum sub-array, the default sub-array must be continuous, the topic reminds us must be in O (n) time complexity is completed, I tried the next brute force cannot pass OJ, then according to the topic of the hint tag, We need to use a hash table and accumulate and to do, about the accumulation and usage can be seen in my previous blog range Sum query-immutable, then the accumulation and the benefits are obvious, if the current cumulative and exactly equal to K, then from the beginning to this position of the sub-array is a solution that meets the requirements, But not necessarily the longest subarray, and using a hash table to build the mappings between the accumulation and its coordinates, we analyze the examples given in the topic:

Nums: [1,-1, 5,-2, 3], k = 3

Sums: [1, 0, 5, 3, 6]

We can see that the cumulative and fourth number is 3, and the same as K, then the first four numbers are a sub-array that conforms to test instructions, and then a second example:

Nums: [-2,-1, 2, 1], k = 1

Sums: [-2,-3,-1, 0]

We found that there are no numbers equal to K in the cumulative sum, but we know that the answer to this example is [-1, 2], then we see the third and fourth numbers of the accumulation and the array, can we see some rules, yes, the fourth number 0 minus K, get the third number, this is the law, which is also the accumulation , but because there may be duplicate numbers in the accumulation and array, and the hash table keyword cannot be the same, for example:

Nums: [1, 0,-1], k =-1

Sums: [1, 1, 0]

We find that the first and second numbers of the accumulate and the arrays are all 1, so how to build a map, I think, is to save it with a one-dimensional array and compare it to the first number in the array, and when we've built the hash table, we're going to go through the hash table, and when we accumulate and we update res, We detect the current value minus k The resulting value is not present in the hash table, and if present, update the result, see the code below:

Solution One:

classSolution { Public:    intMaxsubarraylen (vector<int>& Nums,intk) {if(Nums.empty ())return 0; intres =0; Unordered_map<int, vector<int>>m; m[nums[0]].push_back (0); Vector<int> sum =Nums;  for(inti =1; I < nums.size (); ++i) {Sum[i]+ = Sum[i-1];        M[sum[i]].push_back (i); }         for(Auto it:m) {if(It.first = = k) res = max (res, it.second.back () +1); Else if(M.find (it.first-k)! =M.end ()) {Res= Max (res, it.second.back ()-m[it.first-k][0]); }        }        returnRes; }};

However, when I go online to see the solution of the great gods, only to find that my pattern Tucson broken, do not need me to write so complex, we do not need to create an additional accumulation and the array, but directly with a variable sum edge additive processing, and our hash table does not have to establish and one-dimensional array mapping, As long as you save the first occurrence of the cumulative and the position, followed by a direct skip, so that is the longest sub-array, come up with the solution of the person you do not heaven, see the code is as follows:

Solution Two:

classSolution { Public:    intMaxsubarraylen (vector<int>& Nums,intk) {intsum =0, res =0; Unordered_map<int,int>m;  for(inti =0; I < nums.size (); ++i) {sum+=Nums[i]; if(sum = = k) Res = i +1; Else if(M.count (sum-k)) res = max (res, i-m[sum-K]); if(!m.count (sum)) m[sum] =i; }        returnRes; }};

Similar topics:

Minimum Size Subarray Sum

Range Sum query-immutable

Resources:

Https://leetcode.com/discuss/77879/o-n-super-clean-9-line-java-solution-with-hashmap

Leetcode all in one topic summary (continuous update ...)

[Leetcode] Maximum Size subarray Sum Equals K maximum sub-array sum of 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.