java 动态规划解决最大连续子数列和
2024-09-04 12:17:40
很多动态规划算法非常像数学中的递推。我们如果能找到一个合适的递推公式,就能很容易的解决问题。
我们用dp[n]表示以第n个数结尾的最大连续子序列的和,这里第n个数必须在子序列中。于是存在以下递推公式:
dp[n] = max(0, dp[n-1]) + num[n]
仔细思考后不难发现这个递推公式是正确的,则整个问题的答案是max(dp[m]) | m∈[1, N]
。java语言代码如下:
//dp[i] = max{dp[i-1]+num[i],num[i]}
class Solution {
public static int maxSubArray(int[] nums) {
if(nums.length==1){
return nums[0];
}
int res = nums[0];
for(int i = 1;i<nums.length;i++){
nums[i] = Math.max(nums[i-1]+nums[i], nums[i]);
if(res<nums[i]){
res = nums[i];
}
}
return res;
}
public static void main(String[] args){
int[] test = {-2,-1};
int res = maxSubArray(test);
System.out.println(res);
}
}
最新文章
- 第一届山东省ACM——Phone Number(java)
- java图形处理-Java Graphics2D
- C#基础之IL
- git服务器搭建
- c# MVC中 @Styles.Render索引超出下标
- new 的用法
- GlusterFS源代码解析 —— GlusterFS 日志
- 重写扫雷(基于jQuery) 新手 有不足的地方敬请谅解
- android获取在res文件下的图片资源
- ubuntu下的notepad++
- C++ Primer 学习笔记_35_STL实践与分析(9)--map种类(在)
- axis1,xfire,jUnit 测试案列+开Web Service开发指南+axis1.jar下载 代码
- java1.8新特性
- linux系统基础优化16条知识汇总
- 文件夹或者文件比对工具 Beyond Compare
- 使用 NPOI 导出 Excel 文件
- Pytorch之训练器设置
- Elasticsearch拼音分词和IK分词的安装及使用
- 好文章之——PHP系列(一)
- PlayerPrefs Elite v1.4.3
热门文章
- leetcode29 两数相除 int 与移位
- Socket 编程简介
- c# xaml (1)
- macOS 没有鼠标 怎么使用 快捷键
- we have a problem with promise
- js 运算符的执行顺序
- GitHub Actions &; GitHub Secrets
- how to create a ring progress bar in web skills
- how to fetch html content in js
- Node.js &; ES modules &; .mjs