Skip to content

Latest commit

 

History

History
 
 

maximum_size_subarray_sum_equals_k

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

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 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

bruteforce n^2, use a memoized greedy algorithm

  1. to get the longest subarray matching a condition, the start_index is better be small
  2. use hashmap to maintain achieved lengths and values