The length of the longest subarray whose sum is k

Given an array nums and a target value k, find the length of the longest sub-array whose sum is equal to k. If there is no sub-array that meets the requirements, 0 is returned.

Note:
 The sum of the nums array must be within the range of 32-bit signed integers.

Example 1:

Input: nums = [1, -1, 5, -2, 3], k = 3
Output: 4
Explanation: The sum of sub-arrays [1, -1, 5, -2] is equal to 3, and the length is the longest.
Example 2:

Input: nums = [-2, -1, 2, 1], k = 1
Output: 2
Explanation: The sub-array [-1, 2] sum is equal to 1, and the length is the longest.

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/maximum-size-subarray-sum-equals-k
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.


public class 和为k的最长子数组的长度leetcode325 {
    
    
    public static int maxSubArrayLen(int[] nums, int k) {
    
    
        Map<Integer, Integer> map = new HashMap<>(); // map在这里存储sum和对应的下标值
        map.put(0, -1);  // 这里初始化为-1,假设0,j的和为k,那么我们得到的长度就是 j-(-1)
        int sum = 0;
        int len = 0;
        for (int j = 0; j < nums.length; j++) {
    
    
            sum += nums[j];
            int preSum = sum - k;
            if (map.containsKey(preSum)) {
    
    
                len = Math.max(len, j - map.get(preSum));
            }
            if (!map.containsKey(sum)) {
    
    
                map.put(sum, j);
            }
        }
        return len;
    }

    public static void main(String[] args) {
    
    
//        System.out.println(maxSubArrayLen(new int[]{-2,-1,2,1}, 1));
        System.out.println(maxSubArrayLen(new int[]{
    
    1, -1, 5, -2, 3}, 3));
    }
}

Guess you like

Origin blog.csdn.net/liu_12345_liu/article/details/102472197