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; +}