From 5458afb3dc24883fc2cf235c7d61581987169735 Mon Sep 17 00:00:00 2001 From: Umesh7Dixit Date: Tue, 10 Oct 2023 08:43:21 -0700 Subject: [PATCH] Adding cpp program --- Coding/Best Time to Buy and Sell Stock.cpp | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Coding/Best Time to Buy and Sell Stock.cpp diff --git a/Coding/Best Time to Buy and Sell Stock.cpp b/Coding/Best Time to Buy and Sell Stock.cpp new file mode 100644 index 00000000..9c2bb50a --- /dev/null +++ b/Coding/Best Time to Buy and Sell Stock.cpp @@ -0,0 +1,30 @@ +#include +#include +#include + +class Solution { +public: + int maxProfit(std::vector& prices) { + int maxProfit = 0; + int mini = prices[0]; + + for(int i = 1; i < prices.size(); i++) { + int curProfit = prices[i] - mini; + maxProfit = std::max(maxProfit, curProfit); + mini = std::min(mini, prices[i]); + } + + return maxProfit; + } +}; + +int main() { + // Example usage of the Solution class + std::vector prices = {7, 1, 5, 3, 6, 4}; + Solution solution; + int maxProfit = solution.maxProfit(prices); + + std::cout << "Maximum profit: " << maxProfit << std::endl; + + return 0; +}