连续最大子序列和的几种算法
2016-06-26 19:15
344 查看
题目:
连续子序列最大和,其实就是求一个序列中连续的子序列中元素和最大的那个。
比如例如给定序列:
{ -2, 11, -4, 13, -5, -2 }
其最大连续子序列为{ 11, -4, 13 },最大和为20
思路:
1、暴力解决O(N^2)
从0开始遍历,用max存储最大子串和
思路2:动态规划
状态转移方程:dp[j] = max{dp[j-1]+nums[j],nums[j]}
思路3:
遍历求和(贪心)
每次遍历求和sum,如果sum<0,则sum=0,从当前位置开始遍历求和。因为之前sum<0。每次求sum时要更新maxValue
思路4:分治法O(nlogn)效果虽然没有上面好,但想法不错。
想法是:
比如 a b c d e d f g h
maxValue = max{max{L,R},f(mid)}
L:{abcd}的maxValue
R:{dfgh}的maxValue
f(mid):含有e的最大sum串。
T(n) = 2*T(n/2) + O(n)
连续子序列最大和,其实就是求一个序列中连续的子序列中元素和最大的那个。
比如例如给定序列:
{ -2, 11, -4, 13, -5, -2 }
其最大连续子序列为{ 11, -4, 13 },最大和为20
思路:
1、暴力解决O(N^2)
从0开始遍历,用max存储最大子串和
public int maxSubArray1(int[] nums) { int n = nums.length; int Max = Integer.MIN_VALUE; for(int i=0;i<n;i++) { int max = 0; for(int j=i;j<n;j++) { max += nums[j]; if(max >Max){Max = max;} } } return Max; }
思路2:动态规划
状态转移方程:dp[j] = max{dp[j-1]+nums[j],nums[j]}
public int maxSubArray2(int[] nums) { int n = nums.length; int MaxValue = Integer.MIN_VALUE; int curValue = 0; for(int i=0;i<n;i++) { curValue = Math.max(curValue+nums[i], nums[i]); if(curValue>MaxValue) { MaxValue = curValue; } } return MaxValue; }
思路3:
遍历求和(贪心)
每次遍历求和sum,如果sum<0,则sum=0,从当前位置开始遍历求和。因为之前sum<0。每次求sum时要更新maxValue
public class Solution { public int maxSubArray(int[] nums) { int n = nums.length; int MaxValue = Integer.MIN_VALUE; int sum = 0; for(int i=0;i<n;i++) { sum += nums[i]; if(sum>MaxValue) { MaxValue = sum; } if(sum<0) { sum = 0; } } return MaxValue; } }
思路4:分治法O(nlogn)效果虽然没有上面好,但想法不错。
想法是:
比如 a b c d e d f g h
maxValue = max{max{L,R},f(mid)}
L:{abcd}的maxValue
R:{dfgh}的maxValue
f(mid):含有e的最大sum串。
T(n) = 2*T(n/2) + O(n)
public class Solution { public int maxSubArray(int[] nums) //分治法O(nlogn)//非常巧妙 { int n = nums.length; return getMax(nums, 0, n-1); } public int getMax(int[] nums,int begin, int end) { if(begin == end){return nums[begin];} if(begin>end){return Integer.MIN_VALUE;} int mid = (begin+end)/2; int L = getMax(nums, begin, mid-1); int R = getMax(nums, mid+1, end); int maxLeft = Integer.MIN_VALUE,maxRight = Integer.MIN_VALUE; int sum = 0; for(int i = mid-1;i>=begin;i--) { sum += nums[i]; if(sum > maxLeft){maxLeft = sum;} } sum = 0; for(int j = mid+1;j<=end;j++) { sum += nums[j]; if(sum > maxRight){maxRight = sum;} } int max = nums[mid]; max += (maxLeft>=0?maxLeft:0); max += (maxRight>=0?maxRight:0); return Math.max(max, Math.max(L,R)); } }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- C#递归算法之分而治之策略
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- C#算法之大牛生小牛的问题高效解决方法
- C#算法函数:获取一个字符串中的最大长度的数字
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 经典排序算法之冒泡排序(Bubble sort)代码
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法