how to implement the kadane’s algorithm when an array only consists of negative element .
Kadane's algorithm
Hi @souravraj024, considering that u know of kadane’s algo , simple kadane’s algo will give right answer until there is atleast one positive number present in the array and will only fail when all the numbers are negetive
so you can do two things :-
- check if all the numbers are negetive then return the maximum element as answer else just simply apply kadane;s algo
- change your max_ending_here as a[0] and max_so_far as INT_MIN instead of 0 and start your iteration from 1
int max_so_far = INT_MIN;
int max_ending_here = array[0];
for (int i = 1; i < size; i++) {
max_ending_here = max(max_ending_here + array[i], array[i]);
max_so_far = max(max_ending_here, max_so_far);
}
printf("%d\n", max_so_far);