博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode-Maximum Subarray[dp]
阅读量:4683 次
发布时间:2019-06-09

本文共 880 字,大约阅读时间需要 2 分钟。

Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],

the contiguous subarray [4,−1,2,1] has the largest sum = 6.

More practice:

 

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 

标签: Divide and Conquer Array Dynamic Programming

分析:最大连续子和问题,我们可以从头遍历数组,遍历到元素 i 时有两个选择:

1.如果它大于等于零时,那就将它与前面的子和sum相加。

2.如果它小于零时,则由该元素作为下一个子和sum的开头元素

在遍历数组的同时记录最大的子和sumj即为最大连续子和;

这里用动态规划的方法解决,设dp[i]表示从首元素到元素i的最大连续子和,所以有状态转移方程为:

dp[i]=max(dp[i-1]+array[i],array[i]);

参考代码:

1 public class Solution { 2     public int maxSubArray(int[] A) { 3         int len=A.length; 4         int ret=Integer.MIN_VALUE; 5         int dp=0; 6         for(int i=0;i

 

转载于:https://www.cnblogs.com/xiaolu266/p/7141751.html

你可能感兴趣的文章
linux/windows 安装MySQLdb模块
查看>>
规划网站
查看>>
面向对象(基础oop)之属性与构造函数
查看>>
Linux网络栈协议无关层--BSD socket
查看>>
FZU 2202——犯罪嫌疑人——————【思维题】
查看>>
SEO知识图一
查看>>
USACO hamming
查看>>
[开源JVM] yvm - 自制Java虚拟机
查看>>
Open vSwitch安装
查看>>
HashMap、HashTable、LinkedHashMap和TreeMap用法和区别
查看>>
document.domain 跨域问题[转]
查看>>
【Android】 No Activity found to handle Intent.
查看>>
Mysql 模糊匹配(字符串str中是否包含子字符串substr)
查看>>
Struts2 Action名称的搜索顺序
查看>>
C++ sort简单用法
查看>>
Oracle分区索引
查看>>
4.17上午
查看>>
IIS的ISAPI接口简介
查看>>
python:open/文件操作
查看>>
16 乘法口诀输出
查看>>