Maximum Subarray Problem


Description

LeetCode Problem 53.

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

A subarray is a contiguous part of an array.

Example 1:

1
2
3
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2:

1
2
Input: nums = [1]
Output: 1

Example 3:

1
2
Input: nums = [5,4,-1,7,8]
Output: 23

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        if (nums.size() == 0)
            return 0;
        int max_sum = nums[0];
        for (int i = 1; i < nums.size(); i ++) {
            if (nums[i-1] > 0)
                nums[i] += nums[i-1];
        }
        for (int i = 0; i < nums.size(); i ++) {
            if (nums[i] > max_sum)
                max_sum = nums[i];
        }
        return max_sum;
    }
};




Related Posts

Triangle Problem

LeetCode 120. Given a triangle array, return the minimum path...

Pascal's Triangle Problem

LeetCode 118. Given an integer numRows, return the first numRows...

Distinct Subsequences Problem

LeetCode 115. Given two strings s and t, return the...

Best Time To Buy And Sell Stock Problem

LeetCode 121. You are given an array prices where prices[i]...

Best Time To Buy And Sell Stock Iii Problem

LeetCode 123. You are given an array prices where prices[i]...

Best Time To Buy And Sell Stock Ii Problem

LeetCode 122. You are given an integer array prices where...