O(n) C++ Solution


  • -1
    A

    You should consider the solution that all the numbers in array are negative.

    class Solution {
    public:
        int maxSubArray(int A[], int n) {
            int max = -0xffff, sum = 0;
            for(int i = 0; i < n; i++){
               if(sum > 0) sum += A[i];
               else sum = A[i];
               if(max < sum) max = sum;
            }
            return max;
        }
    };

  • 0
    S

    the max init value is tricky when the input value < -1000


  • 0
    A

    I think you should let max = A[0], sum = A[0] and i start with 1


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.