LintCode brush problem --- the largest sub-array

description:

  Given an array of integers, find one of the largest and has a sub-array, and returns its maximum.

 

Example:

  Input: [-2, 2, -3, 4, -1, 2, 1, -5, 3]

  Output: 6

  Explanation: fit the needs of the sub-array [4, -1, 2, 1], and a maximum of 6

 

Problem solving:

  Difficulties: Note the array There are three cases are all negative, all positive, positive or negative.

        Also note was that here was the largest sub-array is the largest continuous array of a son, not a random combination was the largest sub-array

 

Two ways to solve problems:

  1. violent problem solving: two cycles through all the biggest sub-arrays directly found.

 

public int maxSubArray(int[] nums) {
        // write your code here
        int MaxSum=nums[0];
        for(int i=0;i<nums.length;i++){
            int sum = 0;
            for(int j = i; j<nums.length;j++){
                sum += nums[j];
                if(sum > MaxSum){
                    MaxSum = sum;
                }
            }
        }
        return MaxSum;
    }

Analysis of Algorithms:

  First subarray and defines the maximum number of the first array, the first layer is to find the beginning of the cycle of the largest sub-array, the second layer loop to find the end of the maximum subarray.

  The second layer loop subarray also calculated and, when the time and the sub-array is greater than MaxSum, to modify MaxSum = sum;

 

The second solution:

  Divide and conquer ???

  Indeed simple codes, time complexity is O (n)

public int maxSubArray(int[] nums) {
        // write your code here
        int MaxSum=nums[0];
        int sum = 0;
        for(int i=0;i<nums.length;i++){
            sum += nums[i];
            if(sum > MaxSum){
                MaxSum = sum;
            }
            if(sum < 0){
                sum = 0;//子串和为负数, 丢掉
            }
        }
        return MaxSum;
    }

Analysis of Algorithms:

  Also define the maximum subarray and a first array, for one cycle, and the sum of the direct calculation, however, and is negative when the, directly off,

  Even from the start again looking for a full-time negative, sum = 0;. Sum + = nums [i] will find a negative largest.   

Guess you like

Origin www.cnblogs.com/S-Evildoer/p/10962947.html