-1

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 ?

Kyle
  • 154
  • 3
  • 9

1 Answers1

1

max sum is 2147483648

2147483648 (decimal) is 2^31, if your int are on 32 bits 2147483648 overflow for a signed int, so max_sum cannot be 2147483648

use long (supposing on 64b) for sum and left_sum

bruno
  • 32,421
  • 7
  • 25
  • 37
  • I try to use long and long long , and it seems that my computer can only let the value be no more than -2147483648. – Kyle Feb 27 '19 at 12:35
  • warning use the suffix 'l' to force literal value to be a long else is an integer, example `2147483648l` rather than `2147483648`. If you have a doubt about the _sizeof_ of _long_ and _long long_ just add a _printf_ in your code to print their _sizeof_ – bruno Feb 27 '19 at 12:45
  • Thank you so much ! It work ! Turns out I forgot to change other variable that I store the final result. – Kyle Feb 27 '19 at 12:56