image.png
暴力求解法
我们可以穷举所有的买入卖出组合,效率是n的平方
问题转换
image.png使用分治法求解
image.png我们来看下跨域中电的情况
FindMaxCrossMid(A,l,m,r)
leftSum = -无穷大
sum = 0
for i = m downto l
sum = sum+ A[i]
if sum > leftSum
leftSum = sum
minL = i
rightSum = -无穷大
sum = 0
for i = m+1upto r
sum = sum+ A[i]
if sum > rightSum
rightSum = sum
maxR = i
return(minL,maxR,leftSum+rightSum)
FindMaxNum(A,low,high)
if hight == low return(low,high, A[low])
mid = [low+high]/2
(l-low,l-high,l-value) = FindMaxNum(A,low,mid)
(r-low,r-high,r-value) = FindMaxNum(A,mid+1,high)
(c-low,c-high,c-value) = FindMaxCrossMid(A,low,mid,high)
if l-value> c-value and l-value>r-value return (l-low,l-high,l-value)
if r-value> l-value and r-value > c-value return (r-low,r-high,r-value)
return (c-low,c-high,c-value)
网友评论