Saturday, July 24, 2021

Maximum Size Subarray Sum Equals k

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, -15, -23], k = 3, maximum length should be 4, that is [1,-1,5,-2,3]
nums = [-2, -121], 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:

Firstly we set 0 value to -1, then we check every time we have met it or not.

No comments:

Post a Comment