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++实现)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升