给定一个整数数组 nums
,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
进阶:
如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的分治法求解。
c#答案:
public class Solution {
public int MaxSubArray(int[] nums) {
int res = nums[0];int sum = 0;
foreach (var item in nums)
{
if (sum > 0)
{
sum += item;
}
else
{
sum = item;
}
res = Math.Max(res, sum);
}
return res;
}
}
第二种方法:
public static int MaxSubArray(int[] nums)
{
int n = nums.Length;
int[] dp = new int[n];//dp[i] means the maximum subarray ending with A[i];
dp[0] = nums[0];
int max = dp[0];
for (int i = 1; i < n; i++)
{
dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
max = Math.Max(max, dp[i]);
}
return max;
}
//448
第三种:
public static int MaxSubArray(int[] nums)
{
int max = nums[0], dp = nums[0];
for (int i = 1; i < nums.Length; i++)
{
dp = Math.Max(dp + nums[i], nums[i]);
max = Math.Max(max, dp);
}
return max;
}
第四种:
把原字符串分成很多不同的字串,然后求出字串中最大的。
把原字符串分成很多不同的字串,通过max(f+A[i],A[i])就可以搞定,如果之前的对我没贡献,还不如另起一个字串
设状态为 f[j],表示以 S[j] 结尾的最大连续子序列和,状态转移方程如下:
f=max(f+A[i],A[i]);//对于数组里的一个整数,它只有两种 选择:1、加入之前的 SubArray;2. 自己另起一个 SubArray。
maxsum=max(maxsum,f);// 求字串中最大的
class Solution {
public:
int maxSubArray(int A[], int n) {
if(0==n) return 0;
int f=0;//f[j],表示以 A[j] 结尾的最大连续子序列和
int maxsum=A[0];
for(int i=0;i<n;++i)
{
f=max(f+A[i],A[i]);//是否需要另起一个字串,如果之前的对我没贡献,还不如另起一个字串。
maxsum=max(maxsum,f); //字串中最大的
}
return maxsum;
}
};