LeetCode(44) Best Time to Buy and Sell Stock I II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/angelazy/article/details/48677825

Best Time to Buy and Sell Stock I

题目描述

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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

本题的描述可以被简化为,判断一个数列中两个数字(profit = sell - buy)差值(profit)最大的组合,要求sell的index要大于buy的index。

解题方法

我们可以通过遍历一遍数组得到最大的profit。

  • 初始情况buy和sell的index均为0,此时profit = 0;
  • 向后遍历如遇到的index为i的数字小于buy,则计算当前的差值sell - buy,若差值大于当前的profit = sell - buy,否则不更新profit,重新设置buy和sell的index为i;
  • 若遇到index为i的数字大于sell,则设置sell的index为i;
  • 根据上述规则遍历到最后一个元素,最大的profit为当前的profit和sell - buy的差值。

这是因为如果遇到更大的sell值,那肯定会增加profit值,若遇到更小的buy,则在后面的遍历过程中可能会遇到更大的profit。例如:
2 3 9 1 9

  • 第一次交易得到的profit 为 9 - 2 = 7;这里因为9 > 3,所以sell会更新为9。
  • 当遇到1时,小于当前的buy(2),如果不更新buy,则后续卖出时得到的profit肯定是小于buy为1时的。所以我们需要记录之前的profit(7),在后面做可能的新的交易(buy = 1, sell = 9)。
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0;
        int buy = prices[0];
        int sell = buy;
        int profit = 0;
        for(size_t i = 1; i != prices.size(); ++i)
        {
            if(prices[i] > sell)
            {
                sell = prices[i];
            }

            if(prices[i] < buy)
            {
                if(sell - buy > profit)
                    profit = sell - buy;
                sell = buy = prices[i];
            }
        }
        return max(sell - buy, profit);
    }
};

Best Time to Buy and Sell Stock II

题目描述

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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

题目二与题目一的区别在于题目一只能做一次buy与sell,而第二题没有这个限制。因此对于第二题来说,我们可以在 sell涨到巅峰的时候卖出,并在下一次重新买进。

解题代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0;

        int sumOfProfit = 0;
        int buy = prices[0], sell = buy;

        for(size_t i = 1; i != prices.size(); ++i)
        {
            if(prices[i] > sell)
            {
                sell = prices[i];
            }

            if(prices[i] < sell)
            {
                sumOfProfit += sell - buy;
                sell = buy = prices[i];
            }
        }

        return sumOfProfit + (sell - buy);
    }
};

总结

题目一和题目二的不同点在于交易的次数,这两题的代码都比较简单,关键是对规则的理解,自己举出一些实例进行判断。

猜你喜欢

转载自blog.csdn.net/angelazy/article/details/48677825
今日推荐