【LeetCode】122. 买卖股票的最佳时机Ⅱ
官方介绍文档
LeetCode说明连接:122. 买卖股票的最佳时机 II - 力扣(LeetCode)
贪心算法
参考解题思路:买卖股票的最佳时机 II (贪心,清晰图解) - 买卖股票的最佳时机 II - 力扣(LeetCode)
可以直接简化为只要今天比昨天大,就卖出(122. 买卖股票的最佳时机 II - 力扣(LeetCode)中评论点赞数第一的思路)。
class Solution {
public:
int maxProfit(vector<int>& prices) {
size_t nPriceSize = prices.size();
int nMaxProfit = 0;
if (nPriceSize > 1)
{
for (int i = 0; i < nPriceSize - 1; i++)
{
if (prices[i] < prices[i + 1])// 当天和第二天,股票处于上升趋势,即有利可图。
{
nMaxProfit += prices[i + 1] - prices[i];
}
}
}
return nMaxProfit;
}
};
复杂度分析
-
时间复杂度:O(n),因为将数组遍历了一遍。
-
空间复杂度:O(1),只使用了几个常量。

浙公网安备 33010602011771号