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.

Idea 1: For all pairs of integers i and j satisfying 0 <= i  <= j < nums.length, check whether the sum of nums[i..j] is greater than the maximum sum so far, take advange of:

  sum of nums[i..j] = sum of nums[i..j-1] + nums[j]

the sum of all continuous subarray starting at i can be calculated in O(n), hence we have a quadratic algorithm.

Time complexity: O(n2)

Space complexity: O(1)

class Solution {
public int maxSubArray(int[] nums) {
int sz = nums.length;
int maxSumSoFar = Integer.MIN_VALUE; for(int i = 0; i < sz; ++i) {
int sumStartHere = 0;
for(int j = i; j < sz; ++j) {
sumStartHere += nums[j];
maxSumSoFar = Math.max(maxSumSoFar, sumStartHere);
}
}
return maxSumSoFar;
}
}

Idea 1.a:  With the help of a cumulative sum array, cumarr[0...i], which can be computed in linear time,  it allows the sum to be computed quickly,

sum[i..j] = cumarr[j] - cumarr[i-1].

Time complexity: O(n2)

Space complexity: O(n)

class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length < 1) return 0;
int sz = nums.length;
int[] cumuSum = new int[sz]; cumuSum[0] = nums[0];
for(int i = 1; i < sz; ++i) {
cumuSum[i] = cumuSum[i-1] + nums[i];
} int maxSumSoFar = Integer.MIN_VALUE;
for(int i = 0; i < sz; ++i) {
for(int j = i; j < sz; ++j) {
int previousSum = 0;
if(i > 0) {
previousSum = cumuSum[i-1];
}
maxSumSoFar = Math.max(maxSumSoFar, cumuSum[j] - previousSum);
}
} return maxSumSoFar;
}
}
class Solution {
public int maxSubArray(int[] nums) {
if(nums == null || nums.length < 1) return 0;
int sz = nums.length;
int[] cumuSum = new int[sz]; cumuSum[0] = nums[0];
for(int i = 1; i < sz; ++i) {
cumuSum[i] = cumuSum[i-1] + nums[i];
} int maxSumSoFar = Integer.MIN_VALUE;
for(int j = 0; j < sz; ++j) {
maxSumSoFar = Math.max(maxSumSoFar, cumuSum[j]);
for(int i = 1; i <= j; ++i) {
maxSumSoFar = Math.max(maxSumSoFar, cumuSum[j] - cumuSum[i-1]);
}
} return maxSumSoFar;
}
}

Idea 2: divide and conquer. Divide into two subproblems, recusively find the maximum in subvectors(max[i..k], max[k..j]) and find the maximum of crossing subvectors(max[i..k..j]), return the max of max[i..k], max[k..j] and max[i..k..j].

Time complexity: O(nlgn)

Space complexity: O(lgn) the stack

class Solution {
private int maxSubArrayHelper(int[] nums, int l, int u) {
if(l >= u) return Integer.MIN_VALUE;
int mid = l + (u - l)/2; int leftMaxSum = nums[mid];
int sum = 0;
for(int left = mid; left >=l; --left) {
sum += nums[left];
leftMaxSum = Math.max(leftMaxSum, sum);
} int rightMaxSum = 0;
sum = 0;
for(int right = mid+1; right < u; ++right) {
sum += nums[right];
rightMaxSum = Math.max(rightMaxSum, sum);
} return Math.max(leftMaxSum + rightMaxSum,
Math.max(maxSubArrayHelper(nums, l, mid), maxSubArrayHelper(nums, mid+1, u)));
} public int maxSubArray(int[] nums) {
return maxSubArrayHelper(nums, 0, nums.length);
}
}

Idea 3: Extend the solution to the next element in the array. How can we extend a solution for nums[0...i-1] to nums[0..i].

The key is the max sum ended in each element, if extending to the next element,

maxHere(i) = Math.max( maxHere(i-1) + nums[i], nums[i])

maxSoFar = Math.max(maxSoFar, maxHere)

Time compleixty: O(n)

Space complexity: O(1)

class Solution {
public int maxSubArray(int[] nums) {
int maxHere = 0;
int maxSoFar = Integer.MIN_VALUE; for(int num: nums) {
maxHere = Math.max(maxHere, 0) + num;
maxSoFar = Math.max(maxSoFar, maxHere);
} return maxSoFar;
}
}

Idea 3.a: Use the cumulative sum,

maxHere = cumuSum(i) - minCumuSum

cumuSum(i) = cumuSum(i-1) + nums[i]

maxSoFar = Math.max(maxSoFar, maxHere) = Math.max(maxSoFar, cumuSum - minCumuSum)

Time compleixty: O(n)

Space complexity: O(1)

class Solution {
public int maxSubArray(int[] nums) {
int min = 0;
int cumuSum = 0;
int maxSoFar = Integer.MIN_VALUE; for(int num: nums) {
cumuSum += num;
maxSoFar = Math.max(maxSoFar, cumuSum - min);
min = Math.min(min, cumuSum);
} return maxSoFar;
}
}

Maximum Subarray LT53的更多相关文章

  1. [LintCode] Maximum Subarray 最大子数组

    Given an array of integers, find a contiguous subarray which has the largest sum. Notice The subarra ...

  2. 【leetcode】Maximum Subarray (53)

    1.   Maximum Subarray (#53) Find the contiguous subarray within an array (containing at least one nu ...

  3. 算法:寻找maximum subarray

    <算法导论>一书中演示分治算法的第二个例子,第一个例子是递归排序,较为简单.寻找maximum subarray稍微复杂点. 题目是这样的:给定序列x = [1, -4, 4, 4, 5, ...

  4. LEETCODE —— Maximum Subarray [一维DP]

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

  5. 【leetcode】Maximum Subarray

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

  6. maximum subarray problem

    In computer science, the maximum subarray problem is the task of finding the contiguous subarray wit ...

  7. (转)Maximum subarray problem--Kadane’s Algorithm

    转自:http://kartikkukreja.wordpress.com/2013/06/17/kadanes-algorithm/ 本来打算自己写的,后来看到上述链接的博客已经说得很清楚了,就不重 ...

  8. 3月7日 Maximum Subarray

    间隔2天,继续开始写LeetCodeOj. 原题: Maximum Subarray 其实这题很早就看了,也知道怎么做,在<编程珠玑>中有提到,求最大连续子序列,其实只需要O(n)的复杂度 ...

  9. LeetCode: Maximum Product Subarray && Maximum Subarray &子序列相关

    Maximum Product Subarray Title: Find the contiguous subarray within an array (containing at least on ...

随机推荐

  1. 2.7、CDH 搭建Hadoop在安装(使用向导设置群集)

    步骤7:使用向导设置群集 完成“ 群集安装”向导后,“ 群集设置”向导将自动启动.以下部分将指导您完成向导的每个页面: 选择服务 分配角色 设置数据库 查看更改 首次运行命令 恭喜! 选择服务 “ 选 ...

  2. pip安装插件库

    升级:python -m pip install --upgrade pip 读excel:pip install xlrd 写入excel:pip install xlwt

  3. metasploit framework(十):SSH扫描、爆破

    SSH版本扫描 SSH密码爆破 设置爆破字典 run开始

  4. View可以设置tag携带数据

    View可以设置tag携带数据.       例子             初始化:ImageView  iv_brand2              设置:iv_brand2.setTag(strB ...

  5. Django项目的创建与管理和pycharm与Github的秘密

    随笔 - 174  文章 - 21  评论 - 19 Django项目创建与管理   1.主题 这部分教程主要介绍如何通过Pycharm创建.管理.运行一个Django工程.对于Django模块的相关 ...

  6. JS在严格模式和非严格模式的区别

    若想在严格模式下使用JS,需要在文件的第一行加上“use strict”,在实际开发中,常常将“use strict”加入到闭包的内部 具体是: 整个脚本中使用:在这个JavaScript文件开头写' ...

  7. postman使用方法

    Postman sending requests 打开Postman,可以看到界面分成左右两个部分,右边是我们后头要讲的collection,左边是现在要讲的request builder.在requ ...

  8. no module named cv2

    运行python脚本时报错: ImportError: No module named cv2 第一想法: 使用命令: pip install cv2 会报错找不到请求的版本 解决方法: 使用命令 p ...

  9. AVL树与红黑树(R-B树)的区别与联系

    AVL树(http://baike.baidu.com/view/593144.htm?fr=aladdin),又称(严格)高度平衡的二叉搜索树.其他的平衡树还有:红黑树.Treap.伸展树.SBT. ...

  10. TOJ2811: Bessie's Weight Problem(完全背包)

    传送门(<---可以点的) 描述 Bessie, like so many of her sisters, has put on a few too many pounds enjoying t ...