最大子序问题求解算法 笔记
2010-04-21 22:20
471 查看
对于最大子序问题求解的四种算法的总结摘录笔记如下:
暴力法(使用三个循环,复杂度为O(n3))
设法在第一个算法中折除一个循环
采用分治法,再次将复杂度降为O(nlogn)
算法4,复杂度O(n)
暴力法(使用三个循环,复杂度为O(n3))
public class MaxSum{ public static void main(String[] args){ int[] array={-3,4,6,-9,5,-12,3,5}; int maxSum=0; for(int i=0;i<array.length;i++){ for(int j=i;j<array.length;j++){ int thisSum=0; for(int k=i;k<j;k++) thisSum+=array[k]; if(thisSum>maxSum) maxSum=thisSum; } } System.out.println("the maxSum of :"+maxSum); } }
设法在第一个算法中折除一个循环
public class MaxSum{ public static void main(String[] args){ int[] array={-3,4,6,-9,5,-12,3,5}; int maxSum=0; for(int i=0;i<array.length;i++){ int thisSum=0; for(int j=i;j<array.length;j++){ thisSum+=array[j]; if(thisSum>maxSum) maxSum=thisSum; } } System.out.println("the maxSum of :"+maxSum); } }
采用分治法,再次将复杂度降为O(nlogn)
private static int maxSumRec(int[] a,int left,int right){ if(left==right) //base case if(a[left]>0) return a[left]; else return 0; int center=(left+right)/2; int maxLeftSum=maxSumRec(a,left,center); int maxRightSum=maxSumRec(a,center+1,right); int maxLeftBorderSum=0,leftBorderSum=0; for(int i=center;i>=left;i--){ leftBorderSum+=a[i]; if(leftBorderSum>maxLeftBorderSum) maxLeftBorderSum=leftBorderSum; } int maxRightBorderSum=0,rightBorderSum=0; for(int i=center+1;i<=right;i++){ rightBorderSum+=a[i]; if(rightBorderSum>maxRightBorderSum) maxRightBorderSum=rightBorderSum; } return max3(maxLeftSum,maxRightSum,maxLeftBorderSum+maxRightBorderSum); } public static int maxSubSum3(int[] a){ return maxSumRec(a,0,a.length-1); }
算法4,复杂度O(n)
public class MaxSum{ public static void main(String[] args){ int[] array={-3,4,6,-9,5,-12,3,5}; int maxSum=0,thisSum=0; for(int i=0;i<array.length;i++){ thisSum+=array[i]; if(thisSum>maxSum) maxSum=thisSum; else if(thisSum<0) thisSum=0; } System.out.println("the maxSum of :"+maxSum); } }
相关文章推荐
- <笔记><算法导论> 假设求解问题的算法需要f(n)毫秒,对下表中的每个函数f(n)和时间t,确定可以在时间t内求解的问题的最大规模n。
- <笔记><算法导论> 假设求解问题的算法需要f(n)毫秒,对下表中的每个函数f(n)和时间t,确定可以在时间t内求解的问题的最大规模n。
- 算法笔记1-最大子序列和问题的求解
- 算法笔记1-最大子序列和问题的求解
- 【算法学习笔记】19.算法设计初步 最大子列和问题的三种方法
- 算法设计和数据结构学习_3(《数据结构和问题求解》part2笔记)
- 第四章 分治策略 4.1 最大子数组问题 (暴力求解算法)
- 求解最大子序列和问题的线性时间算法
- 最大子数组问题的分治求解算法
- 第四章 分治策略 4.1 最大子数组问题 (暴力求解算法)
- 算法设计和数据结构学习_3(《数据结构和问题求解》part2笔记)
- [算法学习笔记]分治法——最大子序列和问题
- 【数据结构与算法】最大子序列和问题的求解
- 【算法学习】最大子数组问题的分治法求解
- 数据结构据与算法分析中的最大字数列求解问题
- 算法笔记:动态规划求解最长子序列问题
- 0013算法笔记——【动态规划】最大子段和问题,最大子矩阵和问题,最大m子段和问题
- 求解最大子列和问题的四种算法
- 大数据面试题求解:给定n个实数 ,求着n个实数在实轴上向量2个数之间的最大差值,要求线性的时间算法(最大间隙问题)
- 最大子数组求解问题(算法导论)