频道首页
目录
算法进修——力扣0053 最大子数组和
收藏
0
最大子数组和
难度:中等
题目描述
给你一个整数数组 nums
,请你找出一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
**子数组 **是数组中的一个连续部分。
示例1
输入:nums = [-2,1,-3,4,-1,2,1,-5,4] 输出:6
示例2
输入:nums = [1] 输出:1
示例3
输入:nums = [5,4,-1,7,8] 输出:23
题解
直接使用动态规划,规划方程如下:
- f(i) = max{f(i - 1) + nums[i], nums[i]}
想法代码
public class Solution
{
public static void Main(string[] args)
{
int[] nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
Solution solution = new Solution();
int res = solution.MaxSubArray(nums);
Console.WriteLine(res);
}
public int MaxSubArray(int[] nums)
{
int pre = 0, maxAns = nums[0];
foreach (int x in nums)
{
pre = Math.Max(pre + x, x);
maxAns = Math.Max(maxAns, pre);
}
return maxAns;
}
}
主页
会议室
Git管理
文章
云文档
看板