欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C++实现LeetCode(122.买股票的最佳时间之二)

程序员文章站 2022-03-03 11:29:36
[leetcode] 122.best time to buy and sell stock ii 买股票的最佳时间之二say you have an array for which the ...

[leetcode] 122.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).

这道跟之前那道best time to buy and sell stock 买卖股票的最佳时间很类似,但都比较容易解答。这道题由于可以无限次买入和卖出。我们都知道炒股想挣钱当然是低价买入高价抛出,那么这里我们只需要从第二天开始,如果当前价格比之前价格高,则把差值加入利润中,因为我们可以昨天买入,今日卖出,若明日价更高的话,还可以今日买入,明日再抛出。以此类推,遍历完整个数组后即可求得最大利润。代码如下:

c++ 解法:

class solution {
public:
    int maxprofit(vector<int>& prices) {
        int res = 0, n = prices.size();
        for (int i = 0; i < n - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
};

java 解法:

public class solution {
    public int maxprofit(int[] prices) {
        int res = 0;
        for (int i = 0; i < prices.length - 1; ++i) {
            if (prices[i] < prices[i + 1]) {
                res += prices[i + 1] - prices[i];
            }
        }
        return res;
    }
}

类似题目:

best time to buy and sell stock with cooldown

best time to buy and sell stock iv

best time to buy and sell stock iii

best time to buy and sell stock

到此这篇关于c++实现leetcode(122.买股票的最佳时间之二)的文章就介绍到这了,更多相关c++实现买股票的最佳时间之二内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!