LeetCode刷题笔记--121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

Easy

2240112FavoriteShare

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
             Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

思路是用两个指针i和j,从末尾开始,i用来寻找top点,j用来寻找对应top点的bottom点。当i找到后,让j=i-1,找最小j,找到后算一次top和bottom的差,看是否比ans大,如果大,记录下来,小的扔掉。这一句:ans=(ttop-tbottom)>ans?(ttop-tbottom):ans;,然后把i往前移,直到=1.(此处注意不是0,因为如果0是最大值,没有意义)

AC的答案:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int i=prices.size()-1;
        int j=i;
        int ttop=-1;//临时top点
        int tbottom=-1;
        int tprofit=-1;
        int ans=-1;
        while(i>0)
        {
            if(prices[i]>ttop&&prices[i-1]<prices[i])
            {
                ttop=prices[i];
                tbottom=ttop;
                j=i;
                j--;
                if(j==-1)return 0;
                while(j>=0)
                {
                    if(prices[j]<tbottom)tbottom=prices[j];
                    j--;
                }
                ans=(ttop-tbottom)>ans?(ttop-tbottom):ans;
            }
            
            
            i--;
        }
        if(ans==-1)return 0;
        return ans;
        
    }
};

猜你喜欢

转载自blog.csdn.net/vivian0239/article/details/88288451
今日推荐