LeetCode-53-Maximum Subarray
2016-06-22 23:28
330 查看
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
题意:就是求最大字数组和。
思路:
DP问题,O(n)内可破
对于位置arr[0]~arr[i],最大字数组和
arr[0] i==0
maxSum[i]=
max{ maxSum[i-1]+arr[i] , arr[i] } 0<i<arr.length
具体来说该题没必要采用maxSum数组,用一个变量记住最大字数组和即可。
Java代码如下:
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.
题意:就是求最大字数组和。
思路:
DP问题,O(n)内可破
对于位置arr[0]~arr[i],最大字数组和
arr[0] i==0
maxSum[i]=
max{ maxSum[i-1]+arr[i] , arr[i] } 0<i<arr.length
具体来说该题没必要采用maxSum数组,用一个变量记住最大字数组和即可。
Java代码如下:
public class Solution { public int maxSubArray(int[] nums) { int max = nums[0],maxEndingHere = nums[0]; for (int i = 1; i < nums.length; i++) { maxEndingHere = Math.max(maxEndingHere+nums[i],nums[i]); max = Math.max(maxEndingHere,max); } return max; } }
相关文章推荐
- centos 安装openoffice (办公软件 WPS)
- mysql 的主从复制
- C++“引用”的理解
- linux 的网络设置
- Elasticsearch初步使用(安装、Head配置、分词器配置)
- 使用mod_dav_svn模块访问SVN仓库方法揭秘
- python操作mongodb之二聚合查询
- python操作mongodb之基础操作
- 【应用程序无法启动,】_应用程序无法启动,的相关文章,教程,源码
- 虚拟机安装mac os以及xcode
- linux 的网络设置
- eclipse的安卓项目上有感叹号
- Sort List
- Qt之JSON生成与解析
- Junit异常用例写法
- 使用Http协议访问网络--HttpURLConnection
- chinapub读书会第10期:机器学习与人工智能 6月25日相约阿里云+优客工场
- ACMUG第三次技术沙龙北京站·6月18活动总结(附ppt下载链接)
- TCP/UDP Socket编程步骤
- HEAP: Free Heap block xxxxxxxx modified at xxxxxxxx after it was freed