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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

Grandyang   2021-07-26 我要评论
想了解C++实现LeetCode(122.买股票的最佳时间之二)的相关内容吗,Grandyang在本文为您仔细讲解C++实现买股票的最佳时间之二的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C++实现二叉树的中序遍历,C++实现LeetCode二叉树的中序遍历,下面大家一起来学习吧。

[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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们