1. 程式人生 > >Scala Maximum Subarray 最大子串 leetcode 53

Scala Maximum Subarray 最大子串 leetcode 53

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
    }
}