题目来源:https://leetcode.com/problems/maximum-subarray/
问题描述
53. Maximum Subarray
Easy
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
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, 求最大的连续子段和。
------------------------------------------------------------
思路
动态规划,dp[i]表示以位置i结尾的连续子段的最大的和。
------------------------------------------------------------
代码
class Solution {
public int maxSubArray(int[] nums) {
int n = nums.length, i = 0, mymax = Integer.MIN_VALUE;
if (n == 0)
{
return 0;
}
int[] dp = new int[n]; // dp[i]: max sum of contiguous subarray ended with index i
dp[0] = nums[0];
for (i=1; i<n; i++)
{
if (dp[i-1] <= 0)
{
dp[i] = nums[i];
}
else
{
dp[i] = dp[i-1] + nums[i];
}
}
for (i=0; i<n; i++)
{
mymax = Math.max(mymax, dp[i]);
}
return mymax;
}
}