Maximum Number of Non-Overlapping Subarrays With Sum Equals Target LeetCode solution in Java
1class Solution {2public int maxNonOverlapping(int[] nums, int target) {3Map<Integer, Integer> valToPos = new HashMap<>();4int sums = 0;5int count = 0;6int lastEndPos = 0;7valToPos.put(0, 0);8for (int i = 0; i < nums.length; i++) {9sums += nums[i];10int pos = valToPos.getOrDefault(sums - target, -1);11if (pos >= lastEndPos) {12count += 1;13lastEndPos = i + 1;14}15valToPos.put(sums, i + 1);16}17return count;18}19}