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
.
其状态转移公式是:f(i) = max(f(i-1)+nums[i], nums[i]),result=max(f(n))
假设数组为[1,-2,3],
f(3)=max(f(2)+3,3)=3
f(2)=max(f(1)+(-2),-2)=-1
f(1)=1
最终结果是max(f(n))=>f(3)=3
数组在遍历的过程中,每一次都需要做出选择:加上当前下标的值,或者不加。
每次做出的选择都是一个结果,当遍历完成后,在结果中选出最大即可。
同时为了让空间复杂度为O(1),时间复杂度为O(n),每次的这个结果都两两比较。
object Solution {
def maxSubArray(nums: Array[Int]): Int = {var global=nums(0)
var local =nums(0)
for(i<-1 until nums.length){
local=Math.max(nums(i),local+nums(i))
global=Math.max(global,local)
}
global
}
}