DAY 7
0

53. Maximum Subarray

Question

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

Example1

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

Example2

Input: nums = 
Output: 1

Example3

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

Constraints

• 1 <= nums.length <= 3 * 104
• -105 <= nums[i] <= 105

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

解題

Think

• 因為要找的是總和最大的，所以如果今天找的陣列是[-2,1,4,3]，實際來跑一次流程看看。
• 一開始maxSum會是第一個值-2，currentSum則是代表每次子陣列的總和。
• 在Python第七行的這個if判斷，是判斷前面加總的值是不是小於0的，是的話代表不管接下來的元素是正是負都不會讓currentSum更大。所以就讓currentSum從頭計算。
• 最後每次加完新的元素，再將currentSum跟maxSum中比較大的值存回maxSum。

Code

Python

class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSum = nums
currentSum = 0

for num in nums:
if currentSum < 0:
currentSum = 0

currentSum += num
maxSum = max(maxSum, currentSum)

return maxSum

C

int maxSubArray(int* nums, int numsSize){
int maxSum = nums;
int currentSum = 0;

for (int i=0 ; i<numsSize ; i++){
if (currentSum < 0)
currentSum = 0;

currentSum += nums[i];
maxSum = (maxSum > currentSum? maxSum : currentSum);
}

return maxSum;
}

Result

• Python

• • C

• 30天 Leetcode解題之路30