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.

 

题目标签:Array
  这道题目给了我们一个array, 让我们找到一个连续的子数组,它的sum是最大的。题目说明有O(n) 方法和 Divide and conquer 方法。
 
  我们先来看一下O(n) 方法:
    遍历array,对于每一个数字,我们判断,(之前的sum + 这个数字) 和 (这个数字) 比大小,如果(这个数字)自己就比 (之前的sum + 这个数字) 大的话,那么说明不需要再继续加了,直接从这个数字,开始继续,因为它自己已经比之前的sum都大了。
    反过来,如果 (之前的sum + 这个数字)大于 (这个数字)就继续加下去。
    这个方法和Kadane Algorithm 差不多, Kadane 的算法是,如果之前的sum 小于0了,就重新计算sum,如果sum不小于0,那么继续加。
 
 
  接着看一下Divide and conquer 方法:
    对于任何一个array来说,有三种可能:
      1。它的maximum subarray 落在它的左边;
      2。maximum subarray 落在它的右边;
      3。maximum subarray 落在它的中间。
 
    对于第一,二种情况,利用二分法就很容易得到,base case 是如果只有一个数字了,那么就返回。
    对于第三种情况,如果落在中间,那么我们要从左右两边返回的两个 mss 中,挑出一个大的,再从 (左右中大的值) 和 (左+右)中挑出一个大的。具体看下面代码。
 
  

Java Solution 1:

Runtime beats 71.37%

完成日期:03/28/2017

关键词:Array

关键点:基于 Kadane's Algorithm 改变

 public class Solution
{
public int maxSubArray(int[] nums)
{
// Solution 1: O(n)
// check param validation.
if(nums == null || nums.length == 0)
return 0; int sum = 0;
int max = Integer.MIN_VALUE; // iterate nums array.
for (int i = 0; i < nums.length; i++)
{
// choose a larger one between current number or (previous sum + current number).
sum = Math.max(nums[i], sum + nums[i]);
max = Math.max(max, sum); // choose the larger max.
} return max;
} }

Java Solution 2:

Runtime beats 71.37%

完成日期:03/28/2017

关键词:Array

关键点:Kadane's Algorithm

 public class Solution
{
public int maxSubArray(int[] nums)
{
int max_ending_here = 0;
int max_so_far = Integer.MIN_VALUE; for(int i = 0; i < nums.length; i++)
{
if(max_ending_here < 0)
max_ending_here = 0;
max_ending_here += nums[i];
max_so_far = Math.max(max_so_far, max_ending_here);
}
return max_so_far;
} }

Java Solution 3:

Runtime beats 29.96%

完成日期:03/29/2017

关键词:Array

关键点:Divide and Conquer

 public class Solution
{
public int maxSubArray(int[] nums)
{
// Solution 3: Divide and Conquer. O(nlogn)
if(nums == null || nums.length == 0)
return 0; return Max_Subarray_Sum(nums, 0, nums.length-1);
} public int Max_Subarray_Sum(int[] nums, int left, int right)
{
if(left == right) // base case: meaning there is only one element.
return nums[left]; int middle = (left + right) / 2; // calculate the middle one. // recursively call Max_Subarray_Sum to go down to base case.
int left_mss = Max_Subarray_Sum(nums, left, middle);
int right_mss = Max_Subarray_Sum(nums, middle+1, right); // set up leftSum, rightSum and sum.
int leftSum = Integer.MIN_VALUE;
int rightSum = Integer.MIN_VALUE;
int sum = 0; // calculate the maximum subarray sum for right half part.
for(int i=middle+1; i<= right; i++)
{
sum += nums[i];
rightSum = Integer.max(rightSum, sum);
} sum = 0; // reset the sum to 0. // calculate the maximum subarray sum for left half part.
for(int i=middle; i>= left; i--)
{
sum += nums[i];
leftSum = Integer.max(leftSum, sum);
} // choose the max between left and right from down level.
int res = Integer.max(left_mss, right_mss);
// choose the max between res and middle range. return Integer.max(res, leftSum + rightSum); } }

参考资料:

http://www.cnblogs.com/springfor/p/3877058.html

https://www.youtube.com/watch?v=ohHWQf1HDfU

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

LeetCode 53. Maximum Subarray(最大的子数组)的更多相关文章

  1. [array] leetcode - 53. Maximum Subarray - Easy

    leetcode - 53. Maximum Subarray - Easy descrition Find the contiguous subarray within an array (cont ...

  2. 小旭讲解 LeetCode 53. Maximum Subarray 动态规划 分治策略

    原题 Given an integer array nums, find the contiguous subarray (containing at least one number) which ...

  3. 41. leetcode 53. Maximum Subarray

    53. Maximum Subarray Find the contiguous subarray within an array (containing at least one number) w ...

  4. Leetcode#53.Maximum Subarray(最大子序和)

    题目描述 给定一个序列(至少含有 1 个数),从该序列中寻找一个连续的子序列,使得子序列的和最大. 例如,给定序列 [-2,1,-3,4,-1,2,1,-5,4], 连续子序列 [4,-1,2,1] ...

  5. LN : leetcode 53 Maximum Subarray

    lc 53 Maximum Subarray 53 Maximum Subarray Find the contiguous subarray within an array (containing ...

  6. leetcode 53. Maximum Subarray 、152. Maximum Product Subarray

    53. Maximum Subarray 之前的值小于0就不加了.dp[i]表示以i结尾当前的最大和,所以需要用一个变量保存最大值. 动态规划的方法: class Solution { public: ...

  7. leetCode 53.Maximum Subarray (子数组的最大和) 解题思路方法

    Maximum Subarray  Find the contiguous subarray within an array (containing at least one number) whic ...

  8. [LeetCode] 53. Maximum Subarray 最大子数组

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

  9. [LeetCode] Minimum Size Subarray Sum 最短子数组之和

    Given an array of n positive integers and a positive integer s, find the minimal length of a subarra ...

  10. C#解leetcode 53.Maximum Subarray

    Find the contiguous subarray within an array (containing at least one number) which has the largest ...

随机推荐

  1. 多线程:深入Thread.sleep

    一直都说,Threed.sleep是不会释放锁,而wait是释放锁的(对象锁),现理论上来分析一下. 由于CPU分配的每个线程的时间片极为短暂(一般为几十毫秒),所以,CPU通过不停地切换线程执行,这 ...

  2. panda库2

    >>> a=pd.Series([1,2],index=['a','b']) >>> a a 1 b 2 dtype: int64 >>> b=p ...

  3. JSP第四篇【EL表达式介绍、获取各类数据、11个内置对象、执行运算、回显数据、自定义函数、fn方法库】

    什么是EL表达式? 表达式语言(Expression Language,EL),EL表达式是用"${}"括起来的脚本,用来更方便的读取对象! EL表达式主要用来读取数据,进行内容的 ...

  4. String ua = request.getHeader("user-agent")---ua值为null

    最近在修改错误日志,发现总报空指针,追踪代码发现这个ua的值有时候会为null,上网查了半天也无果,按常理说ua的值不可能为null,俩小时没找到原因,只是将ua判null了一下,记录一下,如果有大虾 ...

  5. Django查询数据库性能优化

    现在有一张记录用户信息的UserInfo数据表,表中记录了10个用户的姓名,呢称,年龄,工作等信息. models文件 from django.db import models class Job(m ...

  6. 记录一次无聊的(经历了Nodejs -> Shell -> C)的探索问题过程

    提出问题 在运行项目的服务器的git是1.8.3.1版本的时候,pm2 deploy 项目,服务器fetch不到最新的一次commit. 对于这个问题,在pm2的github也有issues讨论.然后 ...

  7. 第4章 同步控制 Synchronization ----死锁(DeadLock)

    Jeffrey Richter 在他所主持的 Win32 Q&A 专栏(Microsoft Systems Journal,1996/07)中曾经提到过,Windows NT 和 Window ...

  8. APUE 4 - 线程

    对传统的UNIX进程来讲,一个进程中只有一个线程,这就意味着一个进程在同一时刻只能做一件事(即使是多核CPU).使用多线程技术, 我们可以设计程序使得一个进程在同一时刻做多件事.使用多线程编程具有以下 ...

  9. 再起航,我的学习笔记之JavaScript设计模式28(委托模式)

    ## 委托模式 ### 概念介绍 **委托模式(Entrust): **多个对象接收并处理同一请求,他们将请求委托给另一个对象统一处理请求. ### 利用委托优化循环 如果我们有一个需求需要让用户点击 ...

  10. 从入门到精通之Boyer-Moore字符串搜索算法详解

    本文讲述的是Boyer-Moore算法,Boyer-Moore算法作为字符串搜索算法,兴趣之下就想了解这个算法,发现这个算法一开始还挺难理解的,也许是我理解能力不是很好吧,花了小半天才看懂,看懂了过后 ...