Subarray Sum Visualizer with Animation
560. Subarray Sum Equals K
Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.
A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [1, 1, 1], k = 2
Output: 2
Example 2:
Input: nums = [1, 2, 3], k = 3
Output: 2
Constraints:
- 1 <=n ums.length <=2 * 104
- -1000 <=n ums[i] <=1 000
- -107 <=k <=1 07
Enter the array of integers and a target sum (k). The visualizer will show how many subarrays sum up to k.
Java Code: Subarray Sum Equals K
class Solution { public int subarraySum(int[] nums, int k) { Map<Integer, Integer> map = new HashMap<>(); map.put(0, 1); int count = 0; int sum = 0; for(int num : nums) { sum += num; int diff = sum - k; if(map.containsKey(diff)) { count += map.get(diff); } map.put(sum, map.getOrDefault(sum, 0) + 1); } return count; } }
No comments:
Post a Comment