最大子数组
来源:互联网 发布:nodejs 生成json文件 编辑:程序博客网 时间:2024/06/05 14:22
题目原型:
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
.
click to show more practice.
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.
基本思路:
令数组为A,从前往后累加得tmp,sum为最大的累加和。
1、如果A[i]>A[i]+tmp,表示,加了还不如不加,那么初始化tmp,令tmp=A[i]。若tmp>sum,则更新sum 。
2、否则,累加tmp,同时注意更新sum。
public int maxSubArray(int[] A){if(A.length==0||A==null)return 0;int sum = A[0];int tmp = A[0];for(int i = 1;i<A.length;i++){ if(A[i]>tmp+A[i]){ tmp = A[i];}else{tmp+=A[i];}if(sum<tmp)sum = tmp;}return sum;}
0 0
- 求最大子数组
- 求最大子数组
- 子数组和最大
- 求最大子数组
- 最大子数组
- 最大子数组和
- 最大子数组和
- 子数组最大和
- 子数组最大乘积
- 最大子数组
- 最大子数组乘积
- 最大子数组和
- 子数组最大和
- 子数组最大和
- 最大子数组二
- 最大连续子数组
- 最大子数组问题
- 最大子数组算法
- 习近平:使社会主义核心价值观的影响像空气一样无所不在
- 在eclipse上clone Apache的Git报302的问题的解决
- TOJ 3290
- Spring Aop详解
- netstat详解
- 最大子数组
- user32.dll中的所有函数
- C# float
- 移动开发者必须了解的10大跨平台工具
- 变量和数据类型
- ios--遍历Tableview
- 好久没有来CSDN了,这段时间比较忙。。
- 又一API聚集地 3scale成立API Codex
- oracle三种复制技术之比较