325. Maximum Size Subarray Sum Equals k
https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/description/
Given an arraynumsand a target valuek, find the maximum length of a subarray that sums tok. If there isn't one, return 0 instead.
Note: The sum of the entirenumsarray is guaranteed to fit within the 32-bit signed integer range.
Example 1:
Givennums=
[1, -1, 5, -2, 3]
,k=3
, return4
. (because the subarray[1, -1, 5, -2]
sums to 3 and is the longest)Example 2:
Givennums=
[-2, -1, 2, 1]
,k=1
, return2
. (because the subarray[-1, 2]
sums to 1 and is the longest)Follow Up: Can you do it in O(n) time?
Thoughts
数组上和为k的子数组最长长度。找和为k的子数组,presum。
Code
Analysis
做题耗时: 19 min Errors: 1. 还考虑了 pos.containsKey(preSum + k), 对应着sum(i, j) == -k , 不用考虑.
时间O(n), 空间O(n)
Last updated
Was this helpful?