LeetCode OJ 53. 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.
【题目分析】
题目要求我们在给定的一个数组中找出一个数组元素之和最大子数组,并返回最大的和。
【思路】 动态规划
max_sum 必然是以A[i](取值范围为A[0] ~ A[n-1])结尾的某段构成的,也就是说max_sum的candidate必然是以A[i]结果的。如果遍历每个candidate,然后进行比较,那么就能找到最大的max_sum了。
假设把A[i]之前的连续段叫做sum。可以很容易想到:
1. 如果sum>=0,就可以和A[i]拼接在一起构成新的sum'。因为不管A[i]多大,加上一个正数总会更大,这样形成一个新的candidate。
2. 反之,如果sum<0,就没必要和A[I]拼接在一起了。因为不管A[i]多小,加上一个负数总会更小。此时由于题目要求数组连续,所以没法保留原sum,所以只能让sum等于从A[i]开始的新的一段数了,这一段数字形成新的candidate。
3. 如果每次得到新的candidate都和全局的max_sum进行比较,那么必然能找到最大的max sum subarray.
在循环过程中,用max_sum记录历史最大的值。从A[0]到A[n-1]一步一步地进行。
其实上面的思想是最简单的动态规划的思想,用maxl[i]数组表示包含i元素的子数组的最大和,则动态规划的递推公式为:maxl[i+1] = max(maxl[i]+A[i], A[i+1]),即最大值一定是数组当前元素以及数组当前元素和前一结果之和的最大值。接下来整个问题的最大值就是maxl数组中的最大值。
面的分析过程是一个简单的动态规划,这个算法叫做 Kadane's algorithm,参加维基百科:https://en.wikipedia.org/wiki/Maximum_subarray_problem
时间复杂度:O(n) 空间复杂度:O(1)
问题解决了,可是发现了下面的拓展,即分治解决。提到分治,思路来了,当前的最大值等于左侧最大值和右侧最大值中较大的。可是,有一点点问题,这个最大值还有可能是横跨左右两侧的啊。。。
于是,在处理两侧的子问题的时候,需要同时分别计算包含最左端元素的最大值(lres)和包含最右端元素的最大值(rres)。这样,当前的最大值就为“左侧最大值(res1)”、“右侧最大值(res2)”、“左侧含最右端元素的最大值(rres1)及右侧包含最左端元素的最大值(lres2)之和”三者的最大值。
而由于lres可分为只在左侧和也包含右侧两种情况:
- 左侧含最左端元素的最大值(lres1)
- 左侧元素之和加右侧含最左端元素的最大值(all1+lres2)
含最右端元素的最大值同理,即lres = max(lres1, all1 + lres2)和rres = max(rres2, all2 + rres1)。
问题得以解决。至于时间复杂度,个人认为,是n/2 + n/4 + n/8 + ... = O(n)。
public class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int length = nums.length;
if (length == 1){
return nums[0];
}
int currentsum = nums[0];
int maxsum = nums[0];
for (int i = 1; i < length; i++){
if (currentsum >= 0){
currentsum += nums[i];
}
else{
currentsum = nums[i];
}
maxsum = maxsum > currentsum ? maxsum : currentsum;
}
return maxsum;
}
}
【C++代码】分而治之
class Solution{
public:
int maxSubArray(int A[], int n){
int res, lres, rres, all;
maxSubArray(A, , n - , res, lres, rres, all);
return res;
}
private:
void maxSubArray(int A[], int l, int r, int &res, int &lres, int &rres, int &all){
if(l == r)
{
res = lres = rres = all = A[l];
return;
}
int m = (l + r) / ;
int res1, lres1, rres1, all1, res2, lres2, rres2, all2;
maxSubArray(A, l, m, res1, lres1, rres1, all1);
maxSubArray(A, m + , r, res2, lres2, rres2, all2);
res = max(max(res1, res2), rres1 + lres2);
lres = max(lres1, all1 + lres2);
rres = max(rres2, all2 + rres1);
all = all1 + all2;
}
};
LeetCode OJ 53. Maximum Subarray的更多相关文章
- [Leetcode][Python]53: Maximum Subarray
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 53: Maximum Subarrayhttps://leetcode.co ...
- Leetcode之53. Maximum Subarray Easy
Leetcode 53 Maximum Subarray Easyhttps://leetcode.com/problems/maximum-subarray/Given an integer arr ...
- 【LeetCode】53. Maximum Subarray (2 solutions)
Maximum Subarray Find the contiguous subarray within an array (containing at least one number) which ...
- 【一天一道LeetCode】#53. Maximum Subarray
一天一道LeetCode系列 (一)题目 Find the contiguous subarray within an array (containing at least one number) w ...
- 【LeetCode】53. Maximum Subarray 最大子序和 解题报告(Python & C++ & Java)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 暴力解法 动态规划 日期 题目地址: https:/ ...
- [leetcode DP]53. Maximum Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- LeetCode OJ:Maximum Subarray(子数组最大值)
Find the contiguous subarray within an array (containing at least one number) which has the largest ...
- 【Leetcode】53. Maximum Subarray
题目地址: https://leetcode.com/problems/maximum-subarray/description/ 题目描述: 经典的求最大连续子数组之和. 解法: 遍历这个vecto ...
- Leetcode No.53 Maximum Subarray(c++实现)
1. 题目 1.1 英文题目 Given an integer array nums, find the contiguous subarray (containing at least one nu ...
随机推荐
- unity3d打开对话框
最近一直在忙项目,没时间更新博客,这两天趁空封装windows下的打开对话框,支持多选.其他系统可以用ngui或者ugui封装一个. 这里就不上封装的源码了提供dll供小伙伴们使用,如果有需要源码请请 ...
- Git 常用命令 更新与提交
整理了一下Git 常用命令,这个版本还是比较好用的,最后附上个人终结版,帮助你快速上手. 取得Git仓库 初始化一个版本仓库 git init Clone远程版本库 git clone yourgit ...
- libvirt里的面向对象的C语言
C语言:类的声明和定义 // 通用父类的定义 struct _virClass { virClassPtr parent; unsigned int magic; char *name; size_t ...
- 键盘快速启动工具Launchy的简单使用技巧
打开电脑面对林林总总的图标,找到对应的程序,快速启动显得尤为重要.这样有利于提高我们的效率. 好了,直接上图: 就是这款小巧的工具,界面如上. 接下来介绍这款工具的使用技巧. 1.安装成功后:打开工具 ...
- MSSQL2008 中文乱码问题 (引自ljg888的专栏)
PHP向MSSQL2008中写入数据,中文乱码 首先:查看SQLserver编码格式的SQL语句为: SELECT COLLATIONPROPERTY('Chinese_PRC_Stro ...
- vim 撤销 恢复 快捷键
u 撤销上一步的操作 Ctrl+r 恢复上一步被撤销的操作
- json 多重嵌套反序列化和序列化
namespace ConsoleApplication1 { class Program { static void Main(string[] args) ...
- doT模板
框架源码地址 https://github.com/olado/doT <div id="main"> <script id="banner-templ ...
- history对象 back() forward() go() 和pushState() replaceState()
History(Window.history对象)对象保存着用户上网的历史记录.处于安全方面的考虑,开发人员无法得知用户浏览过的URL,但是借由用户访问过的页面列表,同样可以在不知道实际URL的情况下 ...
- RabbitMQ队列
AMQP ,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消息的中间件设计.消息中间件主要用于组件之间的解耦,消息的发送者无 ...