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

Maximum Product Subarray Problem

LeetCode 152. Given an integer array nums, find a contiguous...

House Robber Problem

LeetCode 198. You are a professional robber planning to rob...

Dungeon Game Problem

LeetCode 174. The demons had captured the princess and imprisoned...

Best Time To Buy And Sell Stock IV Problem

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

Palindrome Partitioning II Problem

LeetCode 132. Given a string s, partition s such that...

Triangle Problem

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