[Simple algorithm] 34. The best time to buy and sell stocks

topic:

Given an array whose ith element is the price of a given stock on the ith day.

If you are only allowed to complete at most one trade (i.e. buying and selling a stock), design an algorithm to calculate the maximum profit you can make.

Note that you cannot sell a stock before buying it.

Example 1 :

Input: [ 7 , 1 , 5 , 3 , 6 , 4 ]
Output: 5 
Explanation: Buy on day 2 (stock price = 1 ), sell on day 5 (stock price = 6 ), max profit = 6 - 1 = 5 .
     Note that the profit cannot be 7 - 1 = 6 , because the sell price needs to be greater than the buy price.
Example 2 :

Input: [ 7 , 6 , 4 , 3 , 1 ]
Output: 0 
Explanation: In this case, no trade is completed, so the maximum profit is 0 .

Problem solving ideas:

Subtract the previous day from the next day to get the profit of the next day, and then convert the problem into the problem of finding the maximum subsequence sum.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        vector<int> profit;
        int maxRes = 0;
        int sum = 0;
        
        for(int i = 1; i < prices.size(); ++i){
            profit.push_back(prices[i]-prices[i-1]);
        }
        
        for(int i = 0;i < profit.size();++i){
            sum += profit[i];
            if(sum > 0){
                maxRes = max(sum,maxRes);
            }else{
                sum = 0;
            }
        }
        
        return maxRes;
        
    }
};

 Another solution, today's price minus today's stock minimum value:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        vector<int> minleft(prices.size(),0);
        int res = 0;
        
        if(prices.size() <= 0){
            return 0;
        }
        
        int minVal = INT_MAX;
        for(int i = 0;i < prices.size(); ++i){
            minVal = min (minVal, prices [i]);
            minleft [i] = minVal;
        }
        
        for(int i = 1;i < prices.size(); ++i){
            res = max(prices[i]-minleft[i-1],res);
        }
        
        return res;
    }
};

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325337652&siteId=291194637