LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方案
来源:互联网 发布:免费dede织梦cms模板 编辑:程序博客网 时间:2024/05/17 04:28
原始题目如下,意为寻找数组和最大的子串,返回这个最大和即可。
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
.
最普通的方法就是两层循环来寻找,复杂度为O(n^2).
在木易先森的指导下,有一个极其简单的O(n)复杂度的方法:
- 先找出数组max值,如果max小于0 ,啥也别说了,直接返回max.
- 设置辅助变量currentmax=0;数组从头至尾扫描一遍
- 如果currentmax + A[i] <= 0,意味着这个子串对于我们寻找最大和是没有任何帮助的,此时,直接再置currentmax = 0
- 如果currentmax + A[i] > 0,意味着这个子串的和是有意义的,将这个和跟max比较,时刻保持max的值是当前最理想的最大值
- 最后返回max即可
源代码如下:
public class Solution { public static int maxSubArray(int[] A) { if(A.length == 0) return 0; int max = A[0]; for(int i = 0; i < A.length; i ++) if(A[i] > max) max = A[i]; if(max <= 0) return max; int currentmax = 0; for(int i = 0;i < A.length; i ++){ currentmax += A[i]; if(currentmax <= 0){ currentmax = 0; continue; } else{ if(currentmax > max) max = currentmax; } } return max; }}
0 0
- LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方案
- LeetCode 53. Maximum Subarray O(n)实现
- LeetCode OJ:Maximum Subarray
- [LeetCode OJ]Maximum Subarray
- LeetCode OJ Maximum Subarray
- [leetcode oj]Maximum Product Subarray
- LeetCode OJ Maximum Product Subarray
- <LeetCode OJ> 53. Maximum Subarray
- 六、[LeetCode OJ]Maximum Subarray
- [LeetCode OJ]Maximum Product Subarray
- <LeetCode OJ> 152. Maximum Product Subarray
- leetcode oj java 53. Maximum Subarray
- leetcode oj java 152. Maximum Product Subarray
- leetCode解题报告之O(n)线性时间求最大子序列和(Maximum Subarray)
- LeetCode OJ平台上Sort Colors题目算法探讨
- leetcode 152 O(n)解决方案
- LeetCode Maximum Gap的O(N)解法
- LeetCode OJ算法题(五十二):Maximum Subarray
- RefreshView下拉刷新、上拉加载更多(支持ListView) ...
- Android应用优化(3)APK资源图片优化
- 并不是所有的程序员都适合做技术管理
- quartus II工具2——In-System Memory Content Edit
- 在线文本编辑器cheditor应用实例
- LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方案
- Android应用优化(4)浅谈动画和帧率
- 菜鸟学Java(二十)——你知道long和Long有什么区别吗?
- 01_Java语言基础组成
- MAT内存分析
- 理解TCP/IP协议栈之TCP协议
- Lua快速入门技巧
- Android广播机制实现源码浅析(一)
- IT 证书的重要 ( Microsoft Certified: Everyone else is )