題目
原題頁面:https://leetcode.com/problems/maximum-subarray/
題目型別:Divide and Conquer, Array, Dynamic Programming
難度評價:Medium
類似題目:(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.
分析
找最大和連續子陣列,也是經典題目之一。和Gas Station有點類似的地方是,如果當前的子序列加入第k個元素後,sum小於0(首先說明k本身小於0),則這個子序列的sum對後續的k+1是無益的。而且即使從這個子序列中移除掉部分最左邊的元素,也是沒有用的,因為最左邊的元素的總和一定是大於0的,移除掉會更差。所以此時不如從第k+1個元素從0開始重新sum。
可以想像一副不規則的波形圖,sum就是從x軸的某一點開始的面積圖。x軸上方的是有效面積,x軸下方的負數面積。
程式碼
1 | class Solution: |
