【LeetCode】53. Maximum Subarray
来源:互联网 发布:mac系统机器码怎么查看 编辑:程序博客网 时间:2024/06/18 06:39
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
.
题目大意为在一个字符串中找出一个子串,这个子串要满足其中所有数字相加为所有子串中的最大值。解题思路 从开始处累加,记录下当前最大值,如果前一次累加结果为负值,则直接将之前的累加结果置为零(加上一个负值必然会变小,所以直接去除),一直循环到末尾,就可找出最大值,代码如下:
/** * 累加,算出当前结果和最大值 * 只要前面的结果为负数,直接去除(通过将结果置为0)。 */ public int maxSubArray(int[] nums) { int maxSoFar = Integer.MIN_VALUE; //初始时和最小值比较 int maxEndingHere = 0; for(int i=0;i<nums.length;i++) { if (maxEndingHere<0) {//只要前面的结果为负数,直接去除 maxEndingHere = 0; } maxEndingHere += nums[i]; maxSoFar = Math.max(maxSoFar, maxEndingHere); //记录下当前最大值 } return maxSoFar; }
0 0
- [LeetCode]53.Maximum Subarray
- LeetCode --- 53. Maximum Subarray
- [Leetcode] 53. Maximum Subarray
- [leetcode] 53.Maximum Subarray
- 【leetcode】53. Maximum Subarray
- [leetcode] 53.Maximum Subarray
- 【leetcode】53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- [LeetCode]53. Maximum Subarray
- 53. Maximum Subarray LeetCode
- [LeetCode]53. Maximum Subarray
- leetcode 53. Maximum Subarray
- [leetcode] 53. Maximum Subarray
- LeetCode *** 53. Maximum Subarray
- 【LeetCode】53. Maximum Subarray
- leetcode 53. Maximum Subarray
- LeetCode 53. Maximum Subarray
- Leetcode:53. Maximum Subarray
- MySQL多表联表查询
- CCF NOI1027 数字之和
- go语言调用append之后是否重新分配内存?
- 多项式求和
- 多线程学习笔记(二)之线程安全问题
- 【LeetCode】53. Maximum Subarray
- Linux 下Apache虚拟主机的配置
- import导入工程时出现error:DescriptionResourcePathLocationType Target runtime com.genuitec.runtime.gener
- 2017微软预科生面试总结
- CentOS 7内核配置、编译与安装
- STM32的AFIO时钟何时开启
- poj 3259
- 【IMWeb】作业-select制作
- web项目发布过程