和最大的连续子数组 Maximum Subarray

问题:数组

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

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.ide

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.spa

解决:code

①使用时间复杂度为O(n)的方法解决(耗时16ms),属于一种DP问题:递归

最大连续子串问题,对于一个元素数为n的数组,其含有2^n个子序列和n(n+1)/2个子串。若是使用穷举法,则至少须要O(n^2)的时间才能获得答案。所以采用Jay Kadane 提出的线性时间的最优解法:it

  • 遍历该数组, 在遍历过程当中, 将遍历到的元素依次累加起来, 当累加结果小于或等于0时, 从下一个元素开始,从新开始累加。
  • 累加过程当中, 要用一个变量(max)记录所得到过的最大值
  • 一次遍历以后, 变量 max中存储的即为最大子片断的和值。

【注意】io

  • 最大子片断中不可能包含求和值为负的前缀。 例如 【-2, 1,4】 必然不能是最大子数列, 由于去掉值为负的前缀后【-2,1】, 能够获得一个更大的子数列 【4】、
  • 因此在遍历过程当中,每当累加结果成为一个非正值时, 就应当将下一个元素做为潜在最大子数列的起始元素, 从新开始累加。
  • 因为在累加过程当中, 出现过的最大值都会被记录, 且每个可能成为 最大子数列起始元素 的位置, 都会致使新一轮的累加, 这样就保证了答案搜索过程的完备性和正确性。
  • 子串是指数组中连续的若干个元素,而子序列只要求各元素的顺序与其在数组中一致,而没有连续的要求。

 public class Solution {
    public int maxSubArray(int[] nums) {
        int sum = 0;
        int max = Integer.MIN_VALUE;//若令max的值为0,会致使数组元素全部的和都为0的时候返回错误
        for (int i = 0;i < nums.length ;i ++ ) {
            sum += nums[i];
            if(max < sum){
                max = sum;
            }
            if (sum <= 0) {             
                sum = 0;
            }            
        }
        return max;
    }
}ast

public class Solution {
    public int maxSubArray(int[] nums) {
        int sum = nums[0];
        int max = nums[0];
        for(int i = 1; i < nums.length; i++) {
            sum = nums[i] + Math.max(sum, 0);
            max = Math.max(sum, max);
        }
        return max;
    }
} //13ms

②另外题目要求也能够采用分治法(递归)Divide and Conquer Approach解决该问题,时间复杂度为O(nlgn)。分治法的思想就相似于二分搜索法,咱们须要把数组一分为二,分别找出左边和右边的最大子数组之和,而后还要从中间开始向左右分别扫描,求出的最大值分别和左右两边得出的最大值相比较取最大的那一个。耗时23ms,性能不是很好。

public class Solution {     public int maxSubArray(int[] nums) {         if (nums.length == 0) {             return 0;         }         return divide(nums,0,nums.length - 1);     }     public int divide(int[] nums,int left,int right){         if (left >= right) {//若未写=会提示数组下标越界             return nums[left];         }         int mid = (right - left) / 2 + left;         int lmax = divide(nums,left,mid - 1);         int rmax = divide(nums,mid + 1,right);         int mmax = nums[mid];//初始值为中间值         int sum = mmax;         for (int i = mid - 1;i >= left ;i -- ) {//扫描左半部分             sum += nums[i];             mmax = Math.max(mmax,sum);         }         sum = mmax;         for (int i = mid + 1;i <= right ;i ++ ) {//扫描右半部份             sum += nums[i];             mmax = Math.max(mmax,sum);         }         return Math.max(mmax,Math.max(lmax,rmax));     } }

相关文章
相关标签/搜索