Leetcode - Minimum Size Subarray Sum
Leetcode - Contiguous Array

Leetcode - Maximum Size Subarray Sum Equals k

violet posted @ 5 年前 in 算法 with tags Algorithm Golang hash , 232 阅读

https://leetcode.com/problems/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.

Note:
The sum of the entire nums array is guaranteed to fit within the 32-bit signed integer range.

Example 1:

Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4 
Explanation: The subarray [1, -1, 5, -2] sums to 3 and is the longest.

 

Use a hash to keep every sum for each i. And then use current_sum - previous_sum to see whether the result is equal to k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
func maxSubArrayLen(nums []int, k int) int {
    if len(nums) == 0 {
        return 0
    }
    hash := map[int]int{}
    maxNum := 0
    sum := 0
    for i := 0; i < len(nums); i++ {
        sum += nums[i]
        if sum == k {
            maxNum = i + 1
        } else {
            if val, ok := hash[sum - k]; ok {
                maxNum = max(maxNum, i - val)
            }
        }
        if _, ok := hash[sum]; !ok {
            hash[sum] = i
        }
    }
     
    return maxNum
}
 
func max(a, b int) int {
    if a > b {
        return a
    }
     
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter