diff --git a/121_best_time_to_buy_and_sell_stock/main.cpp b/121_best_time_to_buy_and_sell_stock/main.cpp new file mode 100644 index 0000000..f528370 --- /dev/null +++ b/121_best_time_to_buy_and_sell_stock/main.cpp @@ -0,0 +1,19 @@ +#include +using namespace std; + +class Solution { + public: + int maxProfit(vector& 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; + } +};