給定整數數組nums,找到具備最大總和並返回其總和的連續子數組(包含至少一個數字)。 Example:數組
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
app
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.ide
這是一道很是典型的動態規劃題,爲了求整個字符串最大的子序列和,咱們將先求較小的字符串的最大子序列和。這裏咱們從後向前、從前向後計算都是能夠的。在從前向後計算的方法中,咱們將第i個元素以前最大的子序列和存入一個一維數組dp中,對第i+1個元素來講,它的值取決於dp[i],若是dp[i]是負數,那就沒有必要加上它,由於這隻會拖累子序列的最大和。若是是正數就加上它。最後咱們再講第i+1個元素自身加進去,就獲得了第i+1個元素以前最大的子序列和。spa
時間複雜度 O(n) 空間複雜度 O(n)code
class Solution {
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
int max = nums[0];
dp[0] = nums[0];
for(int i = 1; i < nums.length; i ++) {
dp[i] = dp[i - 1] > 0 ? dp[i - 1] + nums[i] : nums[i];
max = Math.max(dp[i], max);
}
return max;
}
}
複製代碼