千秋为卷,山河作答。

题目描述:

买卖股票的最佳时机 II

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。

在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。

返回 你能获得的 最大 利润

解题代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maxProfit(vector<int>& prices) {
int temp = 0;
int profit = 0;
for(int i = 1;i < prices.size();i++){
temp = prices[i] - prices[i-1];
if(temp > 0) profit += temp;

}
return profit;
}
};

image-20231003201555152

解读与收获:

本题运用了贪心算法,其实是一种取巧方法,贪心算法的要点是每次都取最优解,运用到本题中,其实就是只要今天比昨天的股票有涨值,就出手获得利润,贪心的过程不是最终的购买过程,但可以利用贪心算法计算最大利润。