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. [疯狂Java]JDBC:PreparedStatement预编译执行SQL语句

    1. SQL语句的执行过程——Statement直接执行的弊病: 1) SQL语句和编程语言一样,仅仅就会普通的文本字符串,首先数据库引擎无法识别这种文本字符串,而底层的CPU更不理解这些文本字符串( ...

  2. hibernate中调用query.list()而出现的黄色警告线

    使用hibernate的时候会用到hql语句查询数据库, 那就一定会用到query.list();这个方法, 那就一定会出现一个长长的黄色的警告线, 不管你想尽什么办法, 总是存在, 虽然说这个黄色的 ...

  3. python websocket网页实时显示远程服务器日志信息

    功能:用websocket技术,在运维工具的浏览器上实时显示远程服务器上的日志信息 一般我们在运维工具部署环境的时候,需要实时展现部署过程中的信息,或者在浏览器中实时显示程序日志给开发人员看.你还在用 ...

  4. linux环境下的c++编程

    就C++开发工具而言,与Windows下微软(VC, VS2005等)一统天下相比,Linux/Unix下C++开发,可谓五花八门,各式各样.Emacs, vi, eclipse, anjuta,kd ...

  5. 33. Search in Rotated Sorted Array (Array;Divide-and-Conquer)

    Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 migh ...

  6. Asp.net中GridView使用详解(很全,很经典 转来的)

    Asp.net中GridView使用详解 效果图参考:http://hi.baidu.com/hello%5Fworld%5Fws/album/asp%2Enet中以gv开头的图片 l         ...

  7. Javascript 强制浏览器渲染Dom文档

    在Cordova+Framework7开发Hybrid App时,在iPhone 7上遇到一个诡异的现象(Chrome浏览器.Android都正常):js修改手风琴中的input文本框的值后,但页面仍 ...

  8. nginx配置websocket

    有时候我们需要给websocket服务端做一下nginx的配置,比如需要给websocket服务端做负载均衡,或者,有些系统要求访问websocket的时候不能带端口,这时候我们就需要用nginx来进 ...

  9. 6-完美解决Error:SSL peer shut down incorrectly

    转载自: 完美解决Error:SSL peer shut down incorrectly 打开gradle文件夹下的gradle-wrapper文件 修改其中的配置文件将红色区域修改为http:// ...

  10. stark组件开发之提取公共视图函数

     路由问题, 已经解决! 然后就是视图函数的问题了: 不想重复写的解决途径就是, python  类的继承了! 写一个基类, 基类定义 增删改查. 然后其他的,全部去继承他! from django. ...