feat: 121_best_time_to_buy_and_sell_stock
This commit is contained in:
parent
2687d4f02e
commit
d5f074ae92
19
121_best_time_to_buy_and_sell_stock/main.cpp
Normal file
19
121_best_time_to_buy_and_sell_stock/main.cpp
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
#include <bits/stdc++.h>
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
public:
|
||||||
|
int maxProfit(vector<int>& prices) {
|
||||||
|
int result = 0;
|
||||||
|
int minBuyPrice = prices[0];
|
||||||
|
|
||||||
|
for (int i = 1; i < prices.size(); i++) {
|
||||||
|
int sellPrice = prices[i];
|
||||||
|
int profit = sellPrice - minBuyPrice;
|
||||||
|
minBuyPrice = min(minBuyPrice, sellPrice);
|
||||||
|
result = max(result, profit);
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
};
|
Loading…
x
Reference in New Issue
Block a user