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;
}
};
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » Leetcode No.122 Best Time to Buy and Sell Stock II Easy(c++实现)
自学咖网 » Leetcode No.122 Best Time to Buy and Sell Stock II Easy(c++实现)