当前位置:网站首页>【动态规划】连续子数组的最大和
【动态规划】连续子数组的最大和
2022-07-31 03:06:00 【#小苏打】
动态规划(DP):动态规划中每一个状态一定是由上一个状态推导出来的,有别于贪心,贪心是没有状态推导,而是从局部中选择最优的。
动态规划解题步骤

1:确定dp数组,dp[ i ]为包括下标 i 之前的最大连续子序列和。
2:确定状态转移方程,dp[ i ]有两个方向推出,dp[ i-1 ]+nums[ i ] 为加入当前连续子序列和,
num[ i ]为从头开始计算到下标为 i 的子序列和。
3:初始化dp数组,本题目可以看出dp[ i ]依赖于dp[ i-1 ],所以dp[ 0 ]是递推公司基础。
4:确定遍历顺序,本题需要从前往后遍历。
class Solution {
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0]; //初始化dp
int max = dp[0]; //作为一个中间变量输出最大值
for(int i = 1;i<nums.length;i++){
dp[i] = Math.max(dp[i-1]+nums[i],nums[i]); //状态转移方程
max = Math.max(max,dp[i]);
}
return max;
}
}边栏推荐
- [Godot][GDScript] 2D cave map randomly generated
- 12 磁盘相关命令
- Uninstallation of mysql5.7.37 under CentOS7 [perfect solution]
- YOLOV5学习笔记(三)——网络模块详解
- JS function this context runtime syntax parentheses array IIFE timer delay self.backup context call apply
- 【shell基础】判断目录是否为空
- 10 Permission introduction
- 图解lower_bound&upper_bound
- 15、网站统计数据
- 2022 Nioke Multi-School League Game 4 Solution
猜你喜欢

10. Redis implements likes (Set) and obtains the total number of likes

The distance value between two arrays of LeetCode simple questions

CentOS7下mysql5.7.37的安装【完美方案】

【C语言】进制转换一般方法

IDEA 注释报红解决

Project (5) - Small target detection tph-yolov5

10 Permission introduction

6、显示评论和回复

品牌广告投放平台的中台化应用与实践

一份高质量的测试用例如何养成?
随机推荐
2022 Nioke Multi-School League Game 4 Solution
【编译原理】词法分析程序设计原理与实现
IDEA 注释报红解决
[Android] Room - Alternative to SQLite
Mysql 45讲学习笔记(二十四)MYSQL主从一致
7. List of private messages
分布式与集群是什么 ? 区别是什么?
Map.Entry理解和应用
YOLOV5 study notes (2) - environment installation + operation + training
CentOS7下mysql5.7.37的安装【完美方案】
【CocosCreator 3.5】CocosCreator 获取网络状态
15. Website Statistics
【C语言】三子棋(经典解法+一览图)
学习DAVID数据库(1)
遗留系统的自动化策略
8. Unified exception handling (controller notifies @ControllerAdvice global configuration class, @ExceptionHandler handles exceptions uniformly)
[Compilation principle] Lexical analysis program design principle and implementation
[C language foundation] Solve C language error: expected ';', ',' or ')' before '&' token
10. Redis implements likes (Set) and obtains the total number of likes
Detailed explanation of TCP (3)