Leetcode No.122 Best Time to Buy and Sell Stock II Easy(c++实现)

2021/7/10 11:06:34

本文主要是介绍Leetcode No.122 Best Time to Buy and Sell Stock II Easy(c++实现),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 题目

1.1 英文题目

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. 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 simultaneously (i.e., you must sell the stock before you buy again).

1.2 中文题目

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

1.3输入输出

输入 输出
prices = [7,1,5,3,6,4] 7
prices = [1,2,3,4,5] 4
prices = [7,6,4,3,1] 0

1.4 约束条件

  • 1 <= prices.length <= 3 * 104
  • 0 <= prices[i] <= 104

2. 实验平台

IDE:VS2019
IDE版本:16.10.1
语言:c++11

3. 分析

这一题可以借鉴121题的方法,也就是Kadane's Algorithm,具体来说就是求出相邻两个元素间的差值,组成数组,再将数组中的正值加到一起,即可。具体代码如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int maxpro = 0;
        for (int i = 1; i < prices.size(); i++)
            maxpro += max(0, prices[i] - prices[i - 1]);
        return maxpro;
    }
};


这篇关于Leetcode No.122 Best Time to Buy and Sell Stock II Easy(c++实现)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程