LeetCode122 Best Time to Buy and Sell Stock II

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

样例

1
2
3
4
5
Input:
[1, 2, 100, 10]

Output:
99

思路

给出每天的股价,每天只能进行一笔交易,可以买入或卖出,问最大的盈利是多少。

如果价格在$[i, j]$天呈现 的趋势,那么在第天买入,第天卖出,至少可以使得利润不会变得更差。

示例图

代码

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size(), ans = 0;
for (int i = 0; i < n - 1; ++i) {
if (prices[i + 1] > prices[i]) {
ans += prices[i + 1] - prices[i];
}
}
return ans;
}
};
分享到 评论