I use the divide and conquer to solve maximum subarray problem. It works fine on most common case but fail on special one. I think the problem might happen here :
struct subarray maximum_crossing(int A[], int low, int mid ,int high){
int left_sum = INT_MIN;
int left_max = mid;
int sum = 0;
for (int i=mid; i >= low; i--){
sum += A[i];
if (sum > left_sum){
left_sum = sum;
left_max = i;
};
};
..........
..........
I test it and it really work well on common case. But When the array looks something like this : {-2147483648, -2147483648, -2147483648}, it will return the maximum subarray is started at 0 and ends at 1, and max sum is 0. I think it's because INT_MIN + INT_MIN will be 0 in C.
Or in {-2147483648, -1, 0}, the code will find the maximum subarray is started at 0 an ended at 1, max sum is 2147483648. Because of this problem, once the array has -2147483648 and other negative value, the code won't work.
I try to use if statement to check A[i]'s value first but I found that it's not a best solution. Because other negative value can still add together to exceed -2147483648. So is there any more suitable way to solve with this kind of case ?