Given the nums an array of integers, and find a maximum of the successive sub-array (sub-array comprising a minimum element) having its maximum and returns.
Example:
Input: [-2,1, -3,4, -1,2,1, -5,4],
output: 6
Explanation: continuous subarray [4, -1,2,1], and the maximum was 6 .
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/maximum-subarray
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
My solution
Normal answers, and the subsequence must be greater than 0. If both ends of the longest sequence length is a maximum value of the array.
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
start = 0
end = len(nums)-1
maxl = None
while start<=end:
while nums[start]<=0 and start<=end:
maxl = max(maxl,nums[start]) if maxl is not None else nums[start]
start+=1
if start>end:
break
while nums[end]<=0 and end>=start:
maxl = max(maxl,nums[start]) if maxl is not None else nums[end]
end = end-1
if start>end:
break
sumr = 0
while sumr>=0 and end>=start:
sumr+=nums[start]
maxl = max(maxl,sumr) if maxl is not None else sumr
start+=1
if start>end:
break
suml = 0
while suml>0 and end>=start:
suml+=nums[end]
maxl = max(maxl,suml) if maxl is not None else suml
end-=1
if start>end:
break
return maxl
Official explanations
class Solution:
def maxSubArray(self, nums: 'List[int]') -> 'int':
n = len(nums)
max_sum = nums[0]
for i in range(1, n):
if nums[i - 1] > 0:
nums[i] += nums[i - 1]
max_sum = max(nums[i], max_sum)
return max_sum