Arena / Problems /

53. Maximum Subarray

Medium 0/10 Thrones Claimed
Prev Next

Problem Specification

LeetCode #53

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example 1
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation:

The subarray [4,-1,2,1] has the largest sum 6.

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

The subarray [1] has the largest sum 1.

Example 3
Input: nums = [5,4,-1,7,8]
Output: 23
Explanation:

The subarray [5,4,-1,7,8] has the largest sum 23.

Constraints
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
Topics & Algorithms
⚔️

Vacant Python Throne

No developer has claimed the Python throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Dynamic Programming by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by using Greedy Algorithm (please see solution 2), yet here we will use another way.
  • For nums[i]:
    1. If the previous sum is negative, we can discard previous sum;
    2. If the previous sum is positive, we can add previous sum to the current sum.
  • Therefore, it meets the characteristics of a dynamic programming problem.
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        dp = nums.copy()

        for i in range(1, len(dp)):
            dp[i] = max(nums[i], dp[i - 1] + nums[i])

        return max(dp)
#2 Greedy Algorithm (Rolling Variables) by Anonymous Developer
0
Approach Intuition:
  • The "greedy" algorithm solution and the "dynamic programming" algorithm solution for this problem are essentially the same, both are "dynamic programming", but the "greedy" algorithm here changes from using the dp one-dimensional array and then reducing one dimension to using only two variables.
  • The "greedy" algorithm here can be called "rolling variables". Just like "rolling array (one-dimensional)" corresponds to a two-dimensional array, one dimension can be reduced by rolling.
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        result = -float('inf')
        pre_sum = 0

        for num in nums:
            pre_sum = max(pre_sum + num, num)
            result = max(result, pre_sum)

        return result
⚔️

Vacant Java Throne

No developer has claimed the Java throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Dynamic Programming by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by using Greedy Algorithm (please see solution 2), yet here we will use another way.
  • For nums[i]:
    1. If the previous sum is negative, we can discard previous sum;
    2. If the previous sum is positive, we can add previous sum to the current sum.
  • Therefore, it meets the characteristics of a dynamic programming problem.
class Solution {
    public int maxSubArray(int[] nums) {
        var dp = nums.clone();

        for (var i = 1; i < dp.length; i++) {
            dp[i] = Math.max(nums[i], dp[i - 1] + nums[i]);
        }

        return IntStream.of(dp).max().getAsInt(); // if you want to beat 99%, refer to C# soluiton's comment 
    }
}
#2 Greedy Algorithm (Rolling Variables) by Anonymous Developer
0
Approach Intuition:
  • The "greedy" algorithm solution and the "dynamic programming" algorithm solution for this problem are essentially the same, both are "dynamic programming", but the "greedy" algorithm here changes from using the dp one-dimensional array and then reducing one dimension to using only two variables.
  • The "greedy" algorithm here can be called "rolling variables". Just like "rolling array (one-dimensional)" corresponds to a two-dimensional array, one dimension can be reduced by rolling.
class Solution {
    public int maxSubArray(int[] nums) {
        int result = Integer.MIN_VALUE;
        int preSum = 0;

        for (int num : nums) {
            preSum = Math.max(preSum + num, num);
            result = Math.max(result, preSum);
        }

        return result;
    }
}
⚔️

Vacant Javascript Throne

No developer has claimed the Javascript throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Dynamic Programming by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by using Greedy Algorithm (please see solution 2), yet here we will use another way.
  • For nums[i]:
    1. If the previous sum is negative, we can discard previous sum;
    2. If the previous sum is positive, we can add previous sum to the current sum.
  • Therefore, it meets the characteristics of a dynamic programming problem.
var maxSubArray = function (nums) {
  const dp = [...nums]

  for (let i = 1; i < dp.length; i++) {
    dp[i] = Math.max(nums[i], dp[i - 1] + nums[i])
  }

  return Math.max(...dp)
};
#2 Greedy Algorithm (Rolling Variables) by Anonymous Developer
0
Approach Intuition:
  • The "greedy" algorithm solution and the "dynamic programming" algorithm solution for this problem are essentially the same, both are "dynamic programming", but the "greedy" algorithm here changes from using the dp one-dimensional array and then reducing one dimension to using only two variables.
  • The "greedy" algorithm here can be called "rolling variables". Just like "rolling array (one-dimensional)" corresponds to a two-dimensional array, one dimension can be reduced by rolling.
/**
 * @param {number[]} nums
 * @return {number}
 */
var maxSubArray = function(nums) {
    let result = -Infinity;
    let preSum = 0;

    for (const num of nums) {
        preSum = Math.max(preSum + num, num);
        result = Math.max(result, preSum);
    }

    return result;
};
⚔️

Vacant Go Throne

No developer has claimed the Go throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Dynamic Programming by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by using Greedy Algorithm (please see solution 2), yet here we will use another way.
  • For nums[i]:
    1. If the previous sum is negative, we can discard previous sum;
    2. If the previous sum is positive, we can add previous sum to the current sum.
  • Therefore, it meets the characteristics of a dynamic programming problem.
func maxSubArray(nums []int) int {
    dp := slices.Clone(nums)

    for i := 1; i < len(nums); i++ {
        dp[i] = max(nums[i], dp[i - 1] + nums[i])
    }

    return slices.Max(dp)
}
#2 Greedy Algorithm (Rolling Variables) by Anonymous Developer
0
Approach Intuition:
  • The "greedy" algorithm solution and the "dynamic programming" algorithm solution for this problem are essentially the same, both are "dynamic programming", but the "greedy" algorithm here changes from using the dp one-dimensional array and then reducing one dimension to using only two variables.
  • The "greedy" algorithm here can be called "rolling variables". Just like "rolling array (one-dimensional)" corresponds to a two-dimensional array, one dimension can be reduced by rolling.
func maxSubArray(nums []int) int {
    result := math.MinInt
    preSum := 0

    for _, num := range nums {
        preSum = max(preSum + num, num)
        if preSum > result {
            result = preSum
        }
    }

    return result
}
⚔️

Vacant Ruby Throne

No developer has claimed the Ruby throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Dynamic Programming by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by using Greedy Algorithm (please see solution 2), yet here we will use another way.
  • For nums[i]:
    1. If the previous sum is negative, we can discard previous sum;
    2. If the previous sum is positive, we can add previous sum to the current sum.
  • Therefore, it meets the characteristics of a dynamic programming problem.
def max_sub_array(nums)
  dp = nums.clone

  (1...dp.size).each do |i|
    dp[i] = [ nums[i], dp[i - 1] + nums[i] ].max
  end

  dp.max
end
#2 Greedy Algorithm (Rolling Variables) by Anonymous Developer
0
Approach Intuition:
  • The "greedy" algorithm solution and the "dynamic programming" algorithm solution for this problem are essentially the same, both are "dynamic programming", but the "greedy" algorithm here changes from using the dp one-dimensional array and then reducing one dimension to using only two variables.
  • The "greedy" algorithm here can be called "rolling variables". Just like "rolling array (one-dimensional)" corresponds to a two-dimensional array, one dimension can be reduced by rolling.
# @param {Integer[]} nums
# @return {Integer}
def max_sub_array(nums)
  result = -Float::INFINITY
  pre_sum = 0

  nums.each do |num|
    pre_sum = [pre_sum + num, num].max
    result = [result, pre_sum].max
  end

  result
end
⚔️

Vacant C# Throne

No developer has claimed the C# throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Dynamic Programming by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by using Greedy Algorithm (please see solution 2), yet here we will use another way.
  • For nums[i]:
    1. If the previous sum is negative, we can discard previous sum;
    2. If the previous sum is positive, we can add previous sum to the current sum.
  • Therefore, it meets the characteristics of a dynamic programming problem.
public class Solution
{
    public int MaxSubArray(int[] nums)
    {
        var dp = (int[])nums.Clone();

        for (var i = 1; i < dp.Length; i++)
        {
            dp[i] = Math.Max(nums[i], dp[i - 1] + nums[i]);
        }

        return dp.Max(); // if you want to beat 99%, you can use a variable to collect the maximum value: `if (dp[i] > result) result = dp[i];`
    }
}
#2 Greedy Algorithm (Rolling Variables) by Anonymous Developer
0
Approach Intuition:
  • The "greedy" algorithm solution and the "dynamic programming" algorithm solution for this problem are essentially the same, both are "dynamic programming", but the "greedy" algorithm here changes from using the dp one-dimensional array and then reducing one dimension to using only two variables.
  • The "greedy" algorithm here can be called "rolling variables". Just like "rolling array (one-dimensional)" corresponds to a two-dimensional array, one dimension can be reduced by rolling.
public class Solution
{
    public int MaxSubArray(int[] nums)
    {
        int result = int.MinValue;
        int preSum = 0;

        foreach (int num in nums)
        {
            preSum = Math.Max(preSum + num, num);
            result = Math.Max(result, preSum);
        }

        return result;
    }
}
⚔️

Vacant C++ Throne

No developer has claimed the C++ throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

Contenders & Community Submissions (2)

Peer solutions & challenges
#1 Dynamic Programming by Anonymous Developer
0
Approach Intuition:
  • This problem can be solved by using Greedy Algorithm (please see solution 2), yet here we will use another way.
  • For nums[i]:
    1. If the previous sum is negative, we can discard previous sum;
    2. If the previous sum is positive, we can add previous sum to the current sum.
  • Therefore, it meets the characteristics of a dynamic programming problem.
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        auto dp = nums;

        for (auto i = 1; i < dp.size(); i++) {
            dp[i] = max(nums[i], dp[i - 1] + nums[i]);
        }

        return *max_element(dp.begin(), dp.end());
    }
};
#2 Greedy Algorithm (Rolling Variables) by Anonymous Developer
0
Approach Intuition:
  • The "greedy" algorithm solution and the "dynamic programming" algorithm solution for this problem are essentially the same, both are "dynamic programming", but the "greedy" algorithm here changes from using the dp one-dimensional array and then reducing one dimension to using only two variables.
  • The "greedy" algorithm here can be called "rolling variables". Just like "rolling array (one-dimensional)" corresponds to a two-dimensional array, one dimension can be reduced by rolling.
class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        int result = INT_MIN;
        int pre_sum = 0;

        for (int num : nums) {
            pre_sum = max(pre_sum + num, num);
            result = max(result, pre_sum);
        }

        return result;
    }
};
⚔️

Vacant Rust Throne

No developer has claimed the Rust throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Swift Throne

No developer has claimed the Swift throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.

⚔️

Vacant Kotlin Throne

No developer has claimed the Kotlin throne for LeetCode #53 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.