Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
class Solution {
public int maxSubArray(int[] nums) {
int maxSum=nums[0];
int maxHere=nums[0];
for(int i=1;i<nums.length;i++)
{
if(maxHere<0)//和楼下的解法是相同的
{
maxHere=nums[i];
}
else
{
maxHere=maxHere+nums[i];
}
if(maxHere>maxSum)
{
maxSum=maxHere;
}
}
return maxSum;
}
}
//动态规划
//本身这道题是不含有最优子结构的,然后是通过动态规划解决另外一个问题,然后由这个问题再去解决本道题的。
Analysis of this problem:
Apparently, this is a optimization problem, which can be usually solved by DP. So when it comes to DP, the first thing for us to figure out is the format of the sub problem(or the state of each sub problem). The format of the sub problem can be helpful when we are trying to come up with the recursive relation.
At first, I think the sub problem should look like: maxSubArray(int A[], int i, int j), which means the maxSubArray for A[i: j]. In this way, our goal is to figure out what maxSubArray(A, 0, A.length - 1) is. However, if we define the format of the sub problem in this way, it's hard to find the connection from the sub problem to the original problem(at least for me). In other words, I can't find a way to divided the original problem into the sub problems and use the solutions of the sub problems to somehow create the solution of the original one.
So I change the format of the sub problem into something like: maxSubArray(int A[], int i), which means the maxSubArray for A[0:i ] which must has A[i] as the end element. Note that now the sub problem's format is less flexible and less powerful than the previous one because there's a limitation that A[i] should be contained in that sequence and we have to keep track of each solution of the sub problem to update the global optimal value. However, now the connect between the sub problem & the original one becomes clearer:
maxSubArray(A, i) =A[i]+ maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0;
class Solution {
public int maxSubArray(int[] nums) {
int dp []=new int[nums.length];//以第i元素为结尾的最大连续子序列和
dp[0]=nums[0];
int max=dp[0];
for(int i=1;i<nums.length;i++)
{
dp[i]=nums[i]+(dp[i-1]>0?dp[i-1]:0);
if(dp[i]>max)
{
max=dp[i];
}
}
return max;
}
}