简繁EN

LeetCodeNo. 023

[LeetCode with Python] 53. Maximum Subarray

Contents

Problem

Problem page: https://leetcode.com/problems/maximum-subarray/
Topics: Divide and Conquer, Array, Dynamic Programming
Difficulty: Medium
Similar problems: (M) Best Time to Buy and Sell Stock, (M) Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.


Analysis

Finding the contiguous subarray with the largest sum is another classic. This is a bit like Gas Station in what happens when sum drops below 0 after we add the element at k to the current subarray (the element at k must itself be negative). Carrying sum forward won't help at k+1. Even dropping some elements from the left end of the subarray won't help. Their sum must be greater than 0, so dropping them would make things worse. We might as well reset sum to 0 and start adding again at k+1.
Picture an irregular waveform. Starting at some point on the x-axis, sum is the area you accumulate as you move along the axis. The area above the x-axis is the useful area, and the area below it is negative.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:

# @param A, a list of integers
# @return an integer
def maxSubArray(self, A):

len_A = len(A)
if 1 == len_A:
return A[0]

max = None
sum = 0
for n in range(0, len_A):
sum += A[n]
if None == max or sum > max:
max = sum
if sum < 0:
sum = 0
continue

return max

Article link: https://xnerv.wang/en/leetcode-maximum-subarray/