Code Logo

Subarray Sum Equals K

Published atDate not available
Hard 0 views
Like0

This challenge becomes much easier once you know exactly what to keep, change, or count. In Subarray Sum Equals K, you are trying to work toward the right number by following one clear idea.

This one is about building the best total or working out a final amount. You may need to choose which values should be included and which ones should be skipped. Sometimes the biggest number is not the smartest first choice if it hurts the rest of the plan. The goal is to finish with the best overall total, not just one good moment.

For example, if the input is nums = [1,1,1], k = 2, the answer is 2. Example with input: nums = [1,1,1], k = 2 Another example is nums = [1,2,3], k = 3, which gives 2. Example with input: nums = [1,2,3], k = 3

This is one of the harder problems, so it is normal if the answer is not obvious right away. The key is thinking about the whole plan, not only one choice at a time.

Example Input & Output

Example 1
Input
nums = [1,1,1], k = 2
Output
2
Explanation

Example with input: nums = [1,1,1], k = 2

Example 2
Input
nums = [1,2,3], k = 3
Output
2
Explanation

Example with input: nums = [1,2,3], k = 3

Example 3
Input
nums = [3,4,7,2,-3,1,4,2], k = 7
Output
4
Explanation

Example with input: nums = [3,4,7,2,-3,1,4,2], k = 7

Algorithm Flow

Recommendation Algorithm Flow for Subarray Sum Equals K
Recommendation Algorithm Flow for Subarray Sum Equals K

Best Answers

java
import java.util.*;
class Solution {
    public int subarray_sum(Object nums, Object k) {
        int[] n_arr = (int[]) nums;
        int target = (int) k;
        int count = 0, current = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        for (int x : n_arr) {
            current += x;
            if (map.containsKey(current - target)) count += map.get(current - target);
            map.put(current, map.getOrDefault(current, 0) + 1);
        }
        return count;
    }
}