lc 689. Maximum Sum of 3 Non-Overlapping Subarrays
https://leetcode.com/problems/maximum-sum-of-3-non-overlapping-subarrays/description/
给一个array,一个k
找到三段连续k长的子数组,使和最大。
为什么是3,不是4,5。三可以往左往右看,找最大。就是本身算一个,左边最大,右边最大。就知道固定当前情况下的最大值。这样遍历一遍就行了。
code:
class Solution: def maxSumOfThreeSubarrays(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ s=sum(nums[:k]) sms=[s] for j in range(k,len(nums)): i=j-k s+=nums[j]-nums[i] sms.append(s) smsl=[(sms[0],0)] for i in range(1,len(sms)): smsl.append(smsl[-1] if smsl[-1][0]>=sms[i] else (sms[i],i)) smsr=[[-1,0] for i in range(len(sms))] smsr[-1]=[sms[-1],len(sms)-1] for i in reversed(range(len(sms)-1)): if smsr[i+1][0]>sms[i]: smsr[i][0]=smsr[i+1][0] smsr[i][1]=smsr[i+1][1] else: smsr[i][0]=sms[i] smsr[i][1]=i maxx=-1 p1=-1 p2=-1 p3=-1 for i in range(k,len(smsl)-k): if sms[i]+smsl[i-k][0]+smsr[i+k][0]>maxx: p1=smsl[i-k][1] p2=i p3=smsr[i+k][1] maxx=sms[i]+smsl[i-k][0]+smsr[i+k][0] return[p1,p2,p3]