What's wrong with my code ? please correct me

import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int test = sc.nextInt();
int counter = 1 ;
while (test != counter){
int arSize = sc.nextInt();
int[] arr = new int[arSize];
for (int i = 0; i < arSize; i++) {
arr[i] = sc.nextInt();
}
result(arr);
counter++;
}
}
static int maxSubArraySum = Integer.MIN_VALUE;

 static void result(int[] arr) {

int maxSubArraySum = arr[0];
int cur_sum = maxSubArraySum;
for (int i = 1; i < arr.length; i++) {
cur_sum = Math.max(arr[i] + cur_sum, arr[i]);
maxSubArraySum = Math.max(cur_sum, maxSubArraySum);
}
System.out.println(maxSubArraySum);
}

}

Hey @vivek4988_7c34775e05f479ae Since you are using Kadane algorithm which state whenever curr sum becomes negative we have to make curr sum = 0
so add a line of code which makes current sum = 0; whenever currsum < 0.

refer to the code link given below I have made changes to you code.
I have made multiple changes code first one is in the main method initially counter should be 0 not 1.
second is there is no need of using global variable. Third is loop in the result function should start from i = 0.Fourth initially cur_sum should be equal to 0.Lastly I have added condition for negative cur_sum;

1 Like

Cool , nicely explained , thanks got it .

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.