Maximum sub-array and maximum average subarray of values

Source: Internet
Author: User
Tags min

1. Maximum sub-array

Given an array of integers, find a sub-array with the maximum and return its maximum and. Sample Example

Given the array [−2,2,−3,4,−1,2,1,−5,3], the conforming Subarray is [4,−1,2,1], and its maximum is 6

Method 1: Greed

  int Maxsubarray (vector<int> nums) {
        //write your code here
        int sum=nums[0];
        int t=sum;
        for (int i=1;i<nums.size (); i++)
        {
            if (t<0) t=0;
            T=t+nums[i];
            if (t>sum) sum=t;
            
        }
        return sum;
    }

Method 2: Divide and conquer

Class Solution {public:/** * @param nums:a List of integers * @return: A integer indicate the sum of Max Subarray */int Maxsubarray (vector<int> nums) {//write your code here return m (nums,0
    , Nums.size ()-1);
        } int Cross (vector<int>nums,int start,int mid,int end) {int leftmax=0;
        int sum=int_min;
            for (int i=mid;i>=start;i--) {leftmax+=nums[i];
        if (Sum<=leftmax) Sum=leftmax;
        } leftmax=sum;
        int rightmax=0;
        Sum=int_min;
            for (int i=mid+1;i<=end;i++) {rightmax+=nums[i];
        if (Sum<=rightmax) Sum=rightmax;
        } Sum+=leftmax;
        
    return sum;
        } int m (vector<int>nums,int Start,int end) {if (start==end) return Nums[start];
        int mid= (start+end)/2;
        int leftmax=m (NUMS,START,MID);
        int rightmax=m (nums,mid+1,end); int MiddLemax=cross (Nums,start,mid,end);
        if (Leftmax>=rightmax&&leftmax>=middlemax) return leftmax;
        else if (Middlemax>=rightmax&&middlemax>=leftmax) return middlemax;
    else return Rightmax;
 }
};

Law III: Violence (slight)

2. Maximum average sub-array

Gives an array of integers with a positive negative. Find such a sub-array whose length is greater than or equal to K, and the average value is maximum.

Sample Example

Given nums = [1, -5,-6, 3], k = 3

return 15.667//(-6 + 50 + 3)/3 = 15.667


To quote others ' ideas

1, the maximum mean of an array of sub-arrays must be between the maximum and minimum values of the array, so the first step of the dichotomy is limited to average in [Min,max].

2, the next thing to do is to constantly narrow the scope until the Max-min small enough (such as 1e-6), then we have the desired results.

The idea of narrowing the scope is as follows:

Each round set mid= (Min+max)/2, and then the original array of each number minus the mid, if you can find (after a reminder, corrected to: greater than or equal to) the sum of K adjacent number is greater than 0, then the final result must be greater than this mid, the next round of search scope in the [mid , Max]. The converse is limited to [Min,mid].

So the key step that we need to solve in the actual algorithm is how to judge "there is a case where the sum of K neighbors is greater than 0".

First, we can use the sum array to store the sum of the original array minus the mid value (Sum[i] to store the sum of the Num[0]-mid to Num[i-1]-mid), when the sum of sum[i] stores exceeds K (that is, i>k). In other words, we guarantee that this sub-array will have a length of k, which can cut down some of the previously dragged numbers. The number of these min_pre is implemented in the code of the link above. Update Min_pre=sum[i-k + 1] When the previously dragged value is less than Min_pre. Sum[i] Stores num[0]~num[i-1] minus the sum of mid, and Min_pre stores num[0]~num[k] minus the sum of mid, so Sum[i]-min_pre gets sum[k+1]~sum[i-1], The sum of the sums it records is the length of the maximum number of subarray that can be found up to num[i].

Code:

Class Solution {public:/** * @param nums a array with positive and negative numbers * @param k an integer  * @return The maximum average */double maxaverage (vector<int>& nums, int k) {//Write
        Your code here double Start=int_max;
        Double end=int_min;
            for (int i=0;i<nums.size (); i++) {if (Nums[i]<=start) start=nums[i];
        if (nums[i]>=end) end=nums[i];
        } int len=nums.size ();
        Double sum[len+1];
        memset (sum,0,sizeof (sum));
            while (end-start>1e-6) {double mid= (start+end)/2;
            Double min_pre=0;
            BOOL Flag=false;
                for (int i=1;i<=nums.size (); i++) {sum[i]=sum[i-1]+nums[i-1]-mid;
                    if (i>=k&&sum[i]-min_pre>=0) {flag=true;
    break;//as long as there is a set of satisfied averages greater than mid can jump out of the inner loop}            if (i>=k) {min_pre=min (min_pre,sum[i-k+1]);
            }} if (flag) Start=mid;
        else End=mid;
    } return start; }
};

3. By doing the second question, I found a way to do the first question.

int Maxsubarray (vector<int> nums) {
        //write your code here
        int sum[nums.size () +1]={0};
        int min_pre=0;
        int maxn=int_min;
        for (int i=1;i<=nums.size (); i++)
        {
            sum[i]=sum[i-1]+nums[i-1];
            if (SUM[I]-MIN_PRE>=MAXN) Maxn=sum[i]-min_pre;
            Min_pre=min (Sum[i],min_pre);
        }
        return MAXN;
}
But in fact, this method is to use the maximum value of the sum series minus the minimum value of the sum sequence, the second question is the same, that is, the current value minus the minimum value, in the process of the iteration to update the minimum value, and finally get the correct answer



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.