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

122. Best Time to Buy and Sell Stock II

Easy

8441201FavoriteShare

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
             Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

Example 2:

Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
             engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

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

这道题我的解题思路和前面一道一样,但是是从前到后移动i和j的。提交的时候特殊情况又没考虑,一种是[],应该返回0,还有一种是末尾有连续相同大小的数字,比如:1,9,6,9,1,7,1,1,5,9,9,9。我到vs中调试才发现自己犯了两个错误,一个错误是在每次拿到bottom时需要把临时存放值清零:tprofit=0,另一个错误是在j移动到最后一位时判断应该是>=,我写成了>.

if (prices[j] >= prices[j - 1] && prices[j] > bottom)tprofit = prices[j] - bottom;就是这一句,注意,最后这个边界值(j为最大)判断不能省略,并且需要加上>=,来避免末尾是连续相同数字的情况下犯错。

各种考虑不周testcase都能测出来,testcase还是很周到的。

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

下面是AC的答案:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        vector<int> tt;
        tt.clear();
        if(prices==tt)return 0;
        int i=0;
        int bottom=0x7fffffff;
        int j=0;
        int tprofit=0;
        int ans=0;
        while(i<prices.size()-1)
        {
            if(prices[i]<bottom&&prices[i+1]>prices[i])
            {
                tprofit=0;
                bottom=prices[i];
                j=i+1;
                if(j>=prices.size())return 0;
                if((j+1)>=prices.size())
                {
                    if(prices[j]>bottom)tprofit=prices[j]-bottom;
                }
                while(j<prices.size()-1)
                {
                    if(prices[j]>bottom&&prices[j+1]<prices[j])
                    {
                        tprofit=prices[j]-bottom;
                        i=j;
                        bottom=0x7fffffff;
                        break;
                    }
                    j++;
                }
                if(prices[j]>=prices[j-1]&&prices[j]>bottom)tprofit=prices[j]-bottom;
               ans+=tprofit; 
            }
            i++;
        }
        return ans;
    }
};