53. Maximum Subarray
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.
題解:
輸入一個數(shù)組,求數(shù)組的連續(xù)子數(shù)組中开皿,最大的一段的和;
原問題:n個數(shù)的數(shù)組(nums)的最大子段和笋妥;
子問題:
一個數(shù)的數(shù)組的最大子段和:dp[0] = nums[0]窄潭;
兩個數(shù)的數(shù)組的最大子段和:兩種情況,加上第一個數(shù)(dp[0] + nums[1])或不加上第一個數(shù)(nums[1]):dp[1] = max(dp[0] + nums[1], nums[1])嫉你;其實也就相當(dāng)于是以第二個數(shù)作為子段結(jié)尾的情況下的最優(yōu)解;然后再取max(dp[0], dp[1])嚷辅;
確認(rèn)狀態(tài):
n個數(shù)的數(shù)組的最大子段和:
以nums[n-1]結(jié)尾的最大子段和前n-1個子段最大和比較油挥,取最大值款熬;
動態(tài)規(guī)劃狀態(tài)轉(zhuǎn)移方程:
以第n個數(shù)結(jié)尾的最大子段和:dp[n-1] = (dp[n-2] + nums[n-1], nums[n-1])
邊界狀態(tài):dp[0] = nums[0]攘乒;
最后輸出:max(dp[0],dp[1]则酝,.....dp[n-1])
My Solution(C/C++)
#include <cstdio>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int maxSubArray(vector<int> &nums) {
vector<int> dp(nums.size() + 3, 0);
if (nums.size() == 0) {
return 0;
}
dp[0] = nums[0];
int max_dp = dp[0];
for (int i = 1; i < nums.size(); i++) {
dp[i] = max(dp[i - 1] + nums[i], nums[i]);
if (max_dp < dp[i]) {
max_dp = dp[i];
}
}
return max_dp;
}
};
int main() {
vector<int> nums;
nums.push_back(-2);
nums.push_back(1);
nums.push_back(-3);
nums.push_back(4);
nums.push_back(-1);
nums.push_back(2);
nums.push_back(1);
nums.push_back(-5);
nums.push_back(4);
Solution s;
printf("最大子段和:%d", s.maxSubArray(nums));
return 0;
}
結(jié)果
最大子段和:6
My Solution 1(Python)
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
sum, result = 0, 0
for i in range(len(nums)):
sum += nums[i]
if sum < 0:
sum = 0
else:
result = max(sum, result)
if result == 0:
return max(nums)
return result
My Solution 2(Python)
class Solution:
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dp = []
if len(nums) == 0:
return []
dp.append(nums[0])
max_dp = dp[-1]
for i in range(1, len(nums)):
dp.append(max(dp[i-1] + nums[i], nums[i]))
if max_dp < dp[-1]:
max_dp = dp[-1]
return max_dp
Reference (轉(zhuǎn))
Python:
class Solution(object):
def maxSubArray(self, nums):
for i in xrange(1,len(nums)):nums[i]=max(nums[i], nums[i]+nums[i-1])
return max(nums)
Java:
class Solution {
public int maxSubArray(int[] A) {
int n = A.length;
int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
dp[0] = A[0];
int max = dp[0];
for(int i = 1; i < n; i++){
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.max(max, dp[i]);
}
return max;
}
}