Wednesday, May 11, 2016

LeetCode Q325: Maximum Size Subarray Sum Equals k

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 [1, -1, 5, -2] sums to 3 and is the longest)
Example 2:
Given nums = [-2, -1, 2, 1]k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?

Solution:
This question remind me of using range sum which require you preprocessing the array and you can get sum of any range in constant time.
Once we preprocess the array, for each location given its range sum starting from 0, to quickly find the part with remaining sum, we should use hash table with range sum as key and array index as content.

No comments:

Post a Comment