【leetcode】Maximum Subarray
来源:互联网 发布:姜大声 知乎 编辑:程序博客网 时间:2024/06/05 13:33
一、问题描述
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
.
二、问题分析
其实这是一个非常经典的题目,wiki链接,解决这个题目的方法一般有两种Kadane法和分治法。题目的tag里给出可以采用DP的方法,然后我就考虑DP的初始状态和状态转移方程,这里分析一下,对于数组中的每一个元素,比如array[0],显然dp[0]=array[0],array[1]呢,这里我们需要考虑的情况有三种①array[1]添加到前面的子序列里②array[1]单独一组③array[1]直接忽视掉,接下来我们需要考虑dp数组到底存的是什么?是最大值吗?如果是最大值,那么我们需要记录子序列的开始和结束位置,并且还要考虑中断的情况,并且这样写起来,状态转移方程需要考虑到请款太多了,我并没有成功。通过参考点这里,给了我思路,dp数组其实存的并非是到当前位置的最大值,而是存的到当前位置的连续子序列的值(连续,但不一定最大),如果这样那么就转化为只有两种情况,要么array[i]单独一组,要么加到前面的dp[i-1]上,那么什么情况呢?显然我们可以考虑dp[i-1]的正负性,如果是负数,那么dp[i]=array[i];如果是正数,dp[i] = dp[i-1]+nums[i];然后维护一个全局的max值即可。
三、Java AC代码
DP
public int maxSubArray(int[] nums) { int[] dp = new int[nums.length];int max = nums[0];dp[0] = nums[0];for(int i=1;i<nums.length;i++){if (dp[i-1]<0) {dp[i] = nums[i];}else {dp[i] = dp[i-1]+nums[i];}max = Math.max(max, dp[i]);}return max; }Kadane(其实将上述的dp进行优化就可以得到)
public int maxSubArray(int[] nums) { int maxSoFar = Integer.MIN_VALUE;int maxEndingHere = 0;for(int i=0;i<nums.length;i++) {if (maxEndingHere<0) {maxEndingHere = 0;}maxEndingHere += nums[i];maxSoFar = Math.max(maxSoFar, maxEndingHere);}return maxSoFar; }
分治法(不太懂,供参考)
class Solution {public: int divide(int A[], int low, int high){ if(low == high) return A[low]; if(low == high-1) return max(A[low]+A[high], max(A[low], A[high])); int mid = (low+high)/2; int lmax = divide(A, low, mid-1); int rmax = divide(A, mid+1, high); int mmax = A[mid]; int tmp = mmax; for(int i = mid-1; i >=low; i--){ tmp += A[i]; if(tmp > mmax) mmax = tmp; } tmp = mmax; for(int i = mid+1; i <= high; i++){ tmp += A[i]; if(tmp > mmax) mmax = tmp; } return max(mmax, max(lmax, rmax)); } int maxSubArray(int A[], int n) { // Note: The Solution object is instantiated only once and is reused by each test case. return divide(A, 0, n-1); } };
0 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
- windows8系统 出现不能关机和重启 但是能够休眠的问题
- 【LEETCODE】236-Lowest Common Ancestor of a Binary Tree
- JS 实现瀑布流
- 将 vlfeat 编译成静态库
- lua开发--字符串,json,编码转换
- 【leetcode】Maximum Subarray
- eclipse连接access结果集自动关闭报错
- 为Hexo博客文章添加关键字
- Android——布局layout中的一些属性
- ZABBIX监控MYSQL
- 日期处理
- git 撤销commit中单个文件的修改
- 对谷歌浏览器滚动条进行样式设置
- js的dom模型