53. Maximum Subarray - CPP - Solution


  • 0
    Y
    // https://en.wikipedia.org/wiki/Maximum_subarray_problem
    // https://github.com/soulmachine/leetcode/raw/master/C%2B%2B/leetcode-cpp.pdf
    class Solution {
    public:
        int maxSubArray(const vector<int>& nums) {
            int result(0);
            if (nums.size() > 0) {
                result = nums[0];
                int max_ending_here(nums[0]);
                if (nums.size() > 1) {
                    for (size_t i = 1; i < nums.size(); ++i) {
                        max_ending_here = max(max_ending_here + nums[i], nums[i]);
                        result = max(max_ending_here, result);
                    }
                }
            }
            return result;
        }
    };

Log in to reply
 

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