[Copy question]:
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:
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?
[Brute force solution]:
Time Analysis:
Spatial Analysis:
[After optimization]:
Time Analysis:
Spatial Analysis:
[Wonderful output CONDITIONS]:
[Wonderful corner case]:
[Thinking questions]:
Think only Max (Max, a) can take the longest, do not know how to write. In fact, the General idea of sum as I increases and grow longer, I give for once again on the line.
[a sentence of thought]:
Gap in a sudden increase in K, index also take the corresponding value can be
[input]: null: Normal: Large: Extra Small: Special cases handled in the program: abnormal conditions (unreasonable input):
[Drawing]:
[One brush]:
- Map.containskey (sum) is useless and must be sum = = k .
[Two brushes]:
[Three brushes]:
[Four brushes]:
[Five brushes]:
[Results of five-minute visual debug]:
[Summary]:
Must consider the gapin the middle. Gap in a sudden increase in K, index also take the corresponding value can be
[Complexity]:time Complexity:o (n) Space complexity:o (n)
[English data structure or algorithm, why not other data structures or algorithms]:
To accumulate with a constant sum, the array cannot:
Sum[i] + = nums[i]; It's like every number has been re-added.
[Algorithmic thinking: Recursion/division/greed]:
[Key templating code]:
[Other solutions]:
[Follow up]:
[The problem given by the LC becomes variable]:
2 Sum:hashmap
[Code Style]:
classSolution { Public intMaxsubarraylen (int[] Nums,intk) {//cc if(Nums = =NULL|| Nums.length = = 0)return0; //Ini:hashmap, MaxHashmap<integer, integer> map =NewHashmap<>(); intmax = 0, sum = 0; //For loop:3 conditions for(inti = 0; i < nums.length; i++) {sum+=Nums[i]; //contains, Gap, not contains if(sum = = k) Max = i + 1; Else if(Map.containskey (sum-k)) max = Math.max (max, i-map.get (Sum-k)); if(!map.containskey (sum)) map.put (sum, i); } returnMax; }}
View Code
325. Maximum Size subarray Sum equals K and the oldest array equal to K