121. The best time to buy and sell stocks (Best Time to Buy and Sell Stock)

Topic Address: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/

A problem-solving ideas: Solution of violence

  According to the topic we know that we know the maximum profit "i" - the difference of "j" can get results, so the time complexity is O (n * n), space complexity is O (1). The following is the source:

  int maxProfit(vector<int>& prices) {
           int size=prices.size();
        if(size<=0)
        {
            return 0;
        }
        int max=0;
        for(int i=0;i<size-1;i++)
        {
            for(int j=i+1;j<size;j++)
            {
                if(prices[j]-prices[i]>max)
                    max=prices[j]-prices[i];
            }
        }
        return max;
    }    

The result is not unexpected overtime.

Problem-solving ideas II:

  The idea is to solve the violence timeout due to many unnecessary calculations, we now open up some ideas.

 

As shown in FIG:

      In fact, the biggest profit figure found in the valley and peak (peak occurs after the peak), the height of the two is the greatest profit . Because the main constraints that the peak occurs after the peak, if we determine that the current peak and valley, where it is the highest peak after appearing to sell the stock.

  After the emergence of a new peak (denoted by P) is lower than the peak current (current), then the maximum profit at this time only two possibilities, one difference is after the current peak and a new peak appeared highest top a difference for the peak appeared after new valley and beyond. So we need to value and record peak of maximum profit, each lower peak occurs, we need to update, because this time the old valley has no effect on the results back.

 int maxProfit(vector<int>& prices) {
           int size=prices.size();
        if(size<=0)
        {
            return 0;
        }
        int min=prices[0];
        int maxprices=-1;
        for(int i=0;i<size;i++)
        {
            if(prices[i]<min)
            {
                min=prices[i];//新的峰谷
            }
            else 
            {
                if(prices[i]-min>maxprices)
                    maxprices=prices[i]-min;
            }
        }
        return  maxprices;
    }

 

Guess you like

Origin www.cnblogs.com/carrollCN/p/11440024.html