很多动态规划算法非常像数学中的递推。我们如果能找到一个合适的递推公式,就能很容易的解决问题。
我们用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);
}
}

最新文章

  1. 第一届山东省ACM——Phone Number(java)
  2. java图形处理-Java Graphics2D
  3. C#基础之IL
  4. git服务器搭建
  5. c# MVC中 @Styles.Render索引超出下标
  6. new 的用法
  7. GlusterFS源代码解析 —— GlusterFS 日志
  8. 重写扫雷(基于jQuery) 新手 有不足的地方敬请谅解
  9. android获取在res文件下的图片资源
  10. ubuntu下的notepad++
  11. C++ Primer 学习笔记_35_STL实践与分析(9)--map种类(在)
  12. axis1,xfire,jUnit 测试案列+开Web Service开发指南+axis1.jar下载 代码
  13. java1.8新特性
  14. linux系统基础优化16条知识汇总
  15. 文件夹或者文件比对工具 Beyond Compare
  16. 使用 NPOI 导出 Excel 文件
  17. Pytorch之训练器设置
  18. Elasticsearch拼音分词和IK分词的安装及使用
  19. 好文章之——PHP系列(一)
  20. PlayerPrefs Elite v1.4.3

热门文章

  1. leetcode29 两数相除 int 与移位
  2. Socket 编程简介
  3. c# xaml (1)
  4. macOS 没有鼠标 怎么使用 快捷键
  5. we have a problem with promise
  6. js 运算符的执行顺序
  7. GitHub Actions &amp; GitHub Secrets
  8. how to create a ring progress bar in web skills
  9. how to fetch html content in js
  10. Node.js &amp; ES modules &amp; .mjs