122. 买卖股票的最佳时机 II
题目:给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
for循环遍历,最大利润等于 当前价格 减 前一个价格与0取最大值的累加。
class Solution {
public:
int maxProfit(vector
<int>& prices
)
{
if(prices
.size() <= 1) return 0;
int maxprofit
= 0;
for(int i
= 1; i
< prices
.size(); i
++)
{
maxprofit
+= max(prices
[i
] - prices
[i
-1], 0);
}
return maxprofit
;
}
};
时间复杂度O(n), 空间复杂度O(1)
[C++]Leetcode超高效刷题顺序及题目详解笔记(持续更新中)