53. Maximum Subarray

Easy

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

package leetcode.easy;

public class MaximumSubarray {
@org.junit.Test
public void test() {
int[] nums = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
System.out.println(maxSubArray(nums));
} public int maxSubArray(int[] nums) {
int max = nums[0];
int count = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > max) {
max = nums[i];
}
count = nums[i];
for (int j = i + 1; j < nums.length; j++) {
count += nums[j];
if (count > max) {
max = count;
}
}
}
return max;
}
}

最新文章

  1. js三种方法添加image
  2. diff 比较两个文件的差异
  3. Strcmp(字符串1,字符串2)函数 Sizeof &amp;&amp; strlen() Substr(a,b)
  4. 转载 jquery $(document).ready() 与window.onload的区别
  5. java泛型的使用
  6. js判断汉字字数
  7. IOS开发之不同版本适配问题2(#ifdef __IPHONE_7_0)(转载)
  8. Linux文件系统介绍
  9. JavaScript函数柯里化的一些思考
  10. JDBC连接SQLServer的几种方式
  11. MultipartEntityBuilder.addTextBody 中文乱码
  12. nginx与ios实现https双向认证
  13. 加盟全景-加盟VR虚拟现实-全景智慧城市
  14. Pivot Table系列之切片器 (Slicer)
  15. 解决linux 乌班图下使用eclipse创建类和其他各种操作进程卡死的问题的一种可能方法
  16. 微信和QQ内置浏览器为什么老是弹停止访问该网页,微信域名被屏蔽的解决办法
  17. windows搭建zabbix agent
  18. Java 关键字 速查表
  19. 7 Make vs Do
  20. Netty 4.1 Getting Start (翻译) + Demo

热门文章

  1. Ajax的简单例子——PHP
  2. SQL SERVER表压缩
  3. 4.Python 进制和位运算
  4. 2019杭电多校第七场 HDU - 6656 Kejin Player——概率&amp;&amp;期望
  5. [bzoj 1471] 不相交路径 (容斥原理)
  6. vuex的使用介绍
  7. 010——C#选择文件路径
  8. Oracle 通过sqlnet.ora文件控制对Oracle数据库的访问
  9. Java 8的Time包常用API
  10. WPF中打开网页的两种方法