java – Find the maximum of non-intersecting .. Details mentioned in description
3609

java – Find the maximum of non-intersecting segments of length 2 (two adjacent elements), such that segments have an equal sum

For ex, given nums = [10, 1, 3, 1, 2, 2, 1, 0, 4], there are three non-overlapping segments, each whose sum is equal to 4: (1, 3), (2, 2), (0, 4).
Expected output = 3
My code below but does not return the correct output, any help would be appreciated?

public static int maxNonOverlapping(int[] nums) {
int[] ends = new int[nums.length + 1];
Map<Integer, Integer> indexs = new HashMap<>();
indexs.put(0,0);
int sum = 0;
int max = 0;
for (int i = 0; i < nums.length; i ++) {
sum += nums[i];
ends[i + 1] = ends[i];
if (indexs.containsKey(sum)) {
ends[i + 1] = Math.max(ends[i + 1], ends[indexs.get(sum)] + 1);
}
indexs.put(sum, i + 1);
}
return ends[nums.length];
}

Comments (5)