Kadane's Algorithm

 Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

 

class Solution {
public:
    int maxSubArray(vector<int>& a) {
        
 
        int max_so_far = INT_MIN, max_ending_here = 0;
 
        for (int i = 0; i < a.size(); i++)
       {
        max_ending_here = max_ending_here + a[i];
        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
 
        if (max_ending_here < 0)
            max_ending_here = 0;
       }
           return max_so_far;
    }
};

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!