Maximum Subarray

Problem

Given an array of integers nums, find the subarray with the largest sum and return the sum.

subarray is a contiguous non-empty sequence of elements within an array.

Examples

Example 1:

Input: nums = [2,-3,4,-2,2,1,-1,4]

Output: 8

Explanation: The subarray [4,-2,2,1,-1,4] has the largest sum 8.

Example 2:

Input: nums = [-1]

Output: -1

Constraints

  • 1 <= nums.length <= 1000
  • -1000 <= nums[i] <= 1000

You should aim for a solution with O(n) time and O(1) space, where n is the size of the input array.

Solution

class Solution {
public:
    int maxSubArray(const vector<int>& nums) {
        // This is the max subaray sum ending at index i
        std::vector<int> memo = nums;
        // Every position has one of two options
        //   start a new subarray at current element
        //   extend subarray that ended at previous element
        // Result is the maximum over all of these
        for (int i = 1; i < nums.size(); ++i) {
            memo[i] = std::max(nums[i], nums[i] + memo[i-1]);
        }
        return *std::ranges::max_element(memo);
    }
};