Maximum Subarray --leetcode
来源:互联网 发布:腾讯云域名认证失败 编辑:程序博客网 时间:2024/06/06 09:17
原题链接:https://oj.leetcode.com/problems/maximum-subarray/
题目的大意是:求一个序列的最大和连续子序列。
解题方法:一维动态规划
解题思路:动态规划方法需要考虑的无非两点:1、维护哪些量? 2、递推关系是什么?
由于最大和连续子序列必定以数组中的某个元素作为末尾元素,所以我们可以求出原数组(用A表示)中以每个下标i上的元素作为尾元素的最大和子序列。然后求出这些序列中和最大的那个就是我们要求的最大和子序列。设以i结尾的子序列最大和为sum_end[i],则递推关系为:sum_end[i+1]=max(sum_end[i]+A[i+1],A[i+1]),即以下标i+1为尾的子序列的最大和要么为sum_end[i]+A[i+1],要么是A[i+1]本身。为了求出这些子序列的最大和,我们只需要维护一个量就可以了。
时间复杂度:O(N) 空间复杂度: O(1)
class Solution {public: int maxSubArray(int A[], int n) { if(n<=0) return 0; int max=A[0]; int pre=A[0]; for(int i=1;i<n;i++) { if(pre+A[i]>A[i]) { pre=pre+A[i]; } else pre=A[i]; if(pre>max) max=pre; } return max; }};
4 0
- 【LeetCode】Maximum Subarray 和 Maximum Product Subarray
- LeetCode: Maximum Subarray
- LeetCode Maximum Subarray
- [Leetcode] Maximum Subarray
- LeetCode: Maximum Subarray
- leetcode 25: Maximum Subarray
- [LeetCode] Maximum Subarray
- [Leetcode] Maximum Subarray
- [LeetCode]Maximum Subarray
- [leetcode]Maximum Subarray
- LeetCode-Maximum Subarray
- [leetcode] Maximum Subarray
- LeetCode 45: Maximum Subarray
- LeetCode - Maximum Subarray
- LeetCode:Maximum Subarray
- LeetCode 53: Maximum Subarray
- 【leetcode】Maximum Subarray
- Leetcode Maximum Subarray
- Microsoft Azure Web Sites应用与实践【2】—— 通过本地IIS 远程管理Microsoft Azure Web Site
- git 查看某个文件的修改历史
- UIImageView的使用方法详细
- 使用Scroll View显示一个文件夹的缩略图,类似图片浏览器(2)
- 大众点评API获取某坐标周边酒店信息
- Maximum Subarray --leetcode
- linux tar 压缩解压文件夹
- 第十二周项目 2 用递归方法求解(1)——求出n的阶乘
- mysql中的LAST_INSERT_ID()分析
- 如何在svn CLI 下添加@2x图片
- VBS 处理断开excel数据链接格式,只保留值
- 在现有SSH项目中提供REST方式的WebService
- PHP实现装饰模式
- 2013年12月 那年的数据导出