Leetcode:121. Best Time to Buy and Sell Stock

Greedy

121. Best Time to Buy and Sell Stock

题目理解:

给出股票的趋势, 找到利润最大的买卖股票的方法

思路:

倒序查找, 找到股票最高价格; 然后找到最高价格前的最低价格, 相减即可得到答案

小结:

这周做了这道简单题, 缓一缓, 其他作业项目好多啊

Submission Detail:

code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <vector>
using namespace std;

class Solution {
public:
int maxPrice = 0;
int max = 0;
int temp;
int maxProfit(vector<int>& prices) {
for (int i = prices.size()-1; i >= 0 ; --i) {
if (prices[i] > maxPrice) {
maxPrice = prices[i];
}
temp = maxPrice - prices[i];
if (temp > max) {
max = temp;
}
}
return max;
}
};