public class maxsubarraysum {
public static void main(String[] args) {
int numbers[] = { 1, -2, 6, -1, 3 };
printmsasum(numbers);
}
public static void printmsasum(int numbers[]) {
int currsum=0;//declared and initialized
int maxsum = Integer.MIN_VALUE;
for (int i = 0; i < numbers.length; i++) {
int start = i;
for (int j = i; j < numbers.length; j++) {
int end = j;
currsum = 0; //here is what i dont understand why i have to again give it zero to run it properly what its is called ? means am i missing any concept? pls help in loops does value changes?
for (int k = start; k <= end; k++) {
currsum += numbers[k];
}
System.out.println(currsum);
if (maxsum < currsum) {
maxsum = currsum;
}
}
}
System.out.println("the maximum sub array sum is = " + maxsum);
}
}
i tried it with only declaring and initializing the currsum variable with zero ,then the output is wrong then inside the second nested loop why i have to initialized it with zero for correct answer?
You are changing
currsumin every iterationcurrsum += numbers[k];, so to check every new result, you have to reset thecurrsum. You don't have to declare it before loops, you can actually declare it in the same place you are setting it to 0.Tip: You also don't have to initalize
startandendvariables, you can useiandj