Problem:
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:
nums = [1, -1, 5, -2, 3], k = 3, maximum length should be 4, that is [1,-1,5,-2,3]
nums = [-2, -1, 2, 1], k = 1 maximum length should be 2, that is [-1,2]
Approach:
This Problem is very similar to this problem, Just we have to modify it a little bit. Again we will solve it using
the Prefix sum method. in every ith position, we will check have we met the (pSum - k) value previously
or not, then simply we will choose maximum length (i-j+1)
Simple code:
No comments:
Post a Comment