LeetCode题解:Maximum Subarray
2016-03-04 09:22
387 查看
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.
题意:找出数组中和最大的子数组
解题思路:DP
代码:
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.
题意:找出数组中和最大的子数组
解题思路:DP
代码:
public class Solution { public int maxSubArray(int[] nums) { int maxSoFar=nums[0]; int maxEndingHere=nums[0]; for (int i = 1; i < nums.length; ++i){ maxEndingHere = Math.max(maxEndingHere + nums[i], nums[i]); maxSoFar = Math.max(maxSoFar, maxEndingHere); } return maxSoFar; } }
相关文章推荐
- 实现PHP框架系列文章(6)mysql数据库方法
- 简单问题
- linux的svn服务器搭建--Subversion Edge
- windows下安装mongodb及其配置
- linux常用命令
- 平衡二叉树
- Handler常见用法
- 位运算
- OS X 不可或缺的套件管理器Homebrew的安装及其常用命令
- 递归求幂
- ASP.NET下载文件几种方式
- 深搜和广搜--原理彼此的优缺点
- The Schröder-Bernstein Theorem
- JavaScript判断浏览器类型及版本
- 嵌入式Linux开发学习笔记:编译与调试
- shell循环
- 欢迎使用CSDN-markdown编辑器
- 【Visual Studio】编译项目报错:无法打开包括文件:“*.h”: No such file or directory
- Java 服务器端修改apk并重新打包签名
- 脚本移植性的问题和解决思路