I was asked to print the number of negative subarrays. I used three loops to fix a starting position, ending position and a loop to print elements of subarray. I need to use count to check if the sum is less than 0. I got wrong output for using the count increment in the inner most loop but got right when I placed the increment right after the closure of inner most loop, after the execution of sum of subarrays. Also when I initialized the sum to 0 within the end of loop produced wrong answer, but initializing it after fixing end position, start of second loop produced correct answer. What's the difference between the two?
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
for (int k = i; k <= j; k++) {
System.out.println(sum+=arr[k]);
if (sum < 0) {
count++;
}
}
}
}
System.out.println(count);
Initializing the sum variable right before each sub array is important, since it needs to be updated to 0 each time you getting new subArray. If you are creating it on loop outer, or inside subArray loop, sum will be changed not as expected, which is bringing your issue. Please refer to below code.