Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

53. Maximum Subarray

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

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

最大子字串,Kadane’s Algorithm問題。

1
2
3
4
5
6
7
8
9
10
11
12
# T: O(n), S: O(n)
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
# Initialize our variables using the first element.
current_subarray = max_subarray = nums[0]

# Start with the 2nd element since we already used the first one.
for num in nums[1:]:
# If current_subarray is negative, throw it away. Otherwise, keep adding to it.
current_subarray = max(num, current_subarray + num) # use current_subarray + num if current_subarray + num bigger then num
max_subarray = max(max_subarray, current_subarray) # compare history max and current max
return max_subarray

如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels