LeetCode53. Maximum Subarray
来源:互联网 发布:怪物猎人p3雷狼数据 编辑:程序博客网 时间:2024/05/21 21:46
53.Maximum Subarray
题意:在一个给定数组中找一个和最大的子数组(至少含有一个元素)。
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.
我的思路:
1、如果加上当前位的和<当前位的值,则舍弃前面的计算结果,直接让sum=当前值,这个sum就是currentSum;
2、设置两个sum,一个是currentSum,用来记录遍历数组过程中的最大和,另一个是maxSum,用来记录历史的currentSum,然后与当前的currentSum相比较,较大值即为maxSum,即maxSum = Math.max(currentSum, maxSum);
public int maxSubArray(int[] nums) { int currentSum = nums[0]; int maxSum = currentSum; for(int i = 1; i < nums.length; i++){ currentSum +=nums[i]; if(currentSum < nums[i]){ currentSum = nums[i]; } maxSum = Math.max(currentSum, maxSum); } return maxSum; }
另一种方法:思路一样,但是写法更加简洁。
public static int maxSubArray1(int[] A) { int maxSoFar=A[0], maxEndingHere=A[0]; for (int i=1;i<A.length;++i){ maxEndingHere= Math.max(maxEndingHere+A[i],A[i]); maxSoFar=Math.max(maxSoFar, maxEndingHere); } return maxSoFar; }
阅读全文
0 0
- LeetCode53:Maximum Subarray
- [Java]LeetCode53 Maximum Subarray
- Leetcode53 Maximum Subarray
- [leetcode53]Maximum Subarray
- LeetCode53. Maximum Subarray
- Leetcode53: Maximum Subarray
- LeetCode53. Maximum Subarray
- LeetCode53. Maximum Subarray题解
- leetcode53~Maximum Subarray
- leetcode53. Maximum Subarray
- LeetCode53 Maximum Subarray
- LeetCode53. Maximum Subarray
- LeetCode53. Maximum Subarray
- leetcode53. Maximum Subarray
- Leetcode53[easy]--Maximum Subarray
- LeetCode53——Maximum Subarray
- Leetcode53——Maximum Subarray
- leetcode53. Maximum Subarray (简单dp)
- Java设计模式
- java多线程之并行和并发
- mySql中Truncate的用法
- window下wps转pdf或html
- 浅谈分布式系统的基本问题:可用性与一致性
- LeetCode53. Maximum Subarray
- 关于在手机浏览器中a标签点击出现淡蓝色背景的解决方法
- 谷歌GDELT数据下载代码
- There is no Action mapped for namespace [/] and action name [struts2Test!test] associated with conte
- 锁屏界面上显示Activity
- 西南交通大学第十三届ACM决赛 D.Music Problem【Bitset+背包/思维+背包】
- mysql数据库读写分离的好处
- gets输入指针
- Mac下一键安装Apache/Nginx+MySQL+PHP开发环境 及各版本测试PHP探针