LeetCode Maximum Subarray
2015-06-28 01:45
316 查看
Description:
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array
the contiguous subarray
Solution:
这道题目是很经典的题目了
求最大区间和
先判断是否都是负的,如果是取最大的
否则,进行累加。当目前累加的结果小于0的时候,重新累加。
累加过程中维护最大值。
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.
Solution:
这道题目是很经典的题目了
求最大区间和
先判断是否都是负的,如果是取最大的
否则,进行累加。当目前累加的结果小于0的时候,重新累加。
累加过程中维护最大值。
public class Solution { public int maxSubArray(int[] nums) { int max = aboveZero(nums); if (max <= 0) return max; int temp = 0; for (int i = 0; i < nums.length; i++) { if (temp + nums[i] < 0) { temp = 0; } else temp += nums[i]; max = Math.max(max, temp); } max = Math.max(max, temp); return max; } public int aboveZero(int[] nums) { int max = nums[0]; for (int i : nums) { if (i > 0) return i; else max = Math.max(max, i); } return max; } }
相关文章推荐
- shell学习指南-阅读笔记
- 数理逻辑量词的引入
- 触屏插件
- 镁光256Gb NAND Flash芯片介绍
- Codeforces Round #310 (Div. 2) A. Case of the Zeros and Ones 水题
- [转]献给迷茫的大多数
- java.io.Writer
- Oracle下的IF EXISTS()
- 进程的等待wait() --多进程编程
- Glibc configure problem: fails sanity check.
- LeetCode Pow(x, n)
- CRC32 Source Code
- 探究requestDisallowInterceptTouchEvent失效的原因
- Android点击20150628_必学必下载
- IOS初体验-Tom猫的开发
- LeetCode_Stack_Largest Rectangle in Histogram
- 灵悟礼品网上专卖店——总结
- Runtime.getRuntime().exec()----记录日志案例
- Codeforces Round #310 (Div. 1) B. Case of Fugitive set
- 数学之美-阅读笔记