★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-surxpdcq-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.git
Example:github
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:算法
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.編程
給定一個整數數組 nums
,找到一個具備最大和的連續子數組(子數組最少包含一個元素),返回其最大和。數組
示例:微信
輸入: [-2,1,-3,4,-1,2,1,-5,4], 輸出: 6 解釋: 連續子數組 [4,-1,2,1] 的和最大,爲 6。
進階:app
若是你已經實現複雜度爲 O(n) 的解法,嘗試使用更爲精妙的分治法求解。ide
動態規劃法:設sum[i]爲以第i個元素結尾且和最大的連續子數組。假設對於元素i,全部以它前面的元素結尾的子數組的長度都已經求得,那麼以第i個元素結尾且和最大的連續子數組實際上,要麼是以第i-1個元素結尾且和最大的連續子數組加上這個元素,要麼是隻包含第i個元素,即sum[i] = max(sum[i-1] + a[i], a[i])。能夠經過判斷sum[i-1] + a[i]是否大於a[i]來作選擇,而這實際上等價於判斷sum[i-1]是否大於0。因爲每次運算只須要前一次的結果,所以並不須要像普通的動態規劃那樣保留以前全部的計算結果,只須要保留上一次的便可,所以算法的時間和空間複雜度都很小spa
12ms:
1 class Solution { 2 func maxSubArray(_ nums: [Int]) -> Int { 3 //動態規劃法 4 var sum:Int = nums[0] 5 var n = nums[0] 6 for i in 1..<nums.count 7 { 8 if n>0 9 { 10 n+=nums[i] 11 } 12 else 13 { 14 n = nums[i] 15 } 16 if sum<n 17 { 18 sum = n 19 } 20 } 21 return sum 22 } 23 }
16ms:
1 class Solution { 2 func maxSubArray(_ nums: [Int]) -> Int { 3 guard nums.count > 0 else { 4 return 0 5 } 6 7 var result = Int(-INT32_MAX - 1) 8 var sum = 0 9 for num in nums { 10 sum += num 11 result = max(result, sum) 12 if sum < 0 { 13 sum = 0 14 } 15 } 16 17 18 return result 19 } 20 }
掃描法:出自《編程珠機》
1 class Solution { 2 func maxSubArray(_ nums: [Int]) -> Int { 3 //掃描法 4 var current:Int = nums[0] 5 var sum = nums[0] 6 //考慮若是全是負數,那麼返回最大的負數, 7 //若是最後的和爲正,那麼就使用掃描法 8 for i in 1..<nums.count 9 { 10 //當前數小於0則捨去, 11 //不然將會影響接下來的和 12 //繼續下一個數 13 if current<0 14 { 15 current = nums[i] 16 } 17 else 18 { 19 //若是當前數不小於0,那麼他會對接下來的和有積極影響 20 current+=nums[i] 21 } 22 //這裏既實現了負數返回最大也實現了掃描法 23 if current>sum 24 { 25 sum = current 26 } 27 //這裏其實已經隱式的列舉了全部可能,保留了全部可能的最大值 28 } 29 return sum 30 } 31 }