From f4a40c61c03440c4e09d33afea209f0d1dfb29aa Mon Sep 17 00:00:00 2001 From: AMBATI KRISHNA TEJA Date: Sat, 14 Oct 2023 12:25:27 +0530 Subject: [PATCH] Create 122. Best Time to Buy and Sell Stock II.cpp --- ...22. Best Time to Buy and Sell Stock II.cpp | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Easy/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.cpp diff --git a/Easy/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.cpp b/Easy/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.cpp new file mode 100644 index 0000000..b4598fa --- /dev/null +++ b/Easy/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.cpp @@ -0,0 +1,46 @@ +#include +#include + +using namespace std; + +class Solution { +public: + int maxProfit(vector& prices) { + int i = 0; + int j = 1; + int maxProfit = 0; + + while(j < prices.size()){ + if(prices[i] < prices[j]){ + maxProfit += prices[j] - prices[i]; + i++; + j++; + }else{ + i++; + j++; + } + } + + return maxProfit; + } +}; + +int main() { + Solution solution; + vector prices; + int n; + cout << "Enter the number of elements: "; + cin >> n; + + cout << "Enter the elements: "; + for (int i = 0; i < n; i++) { + int price; + cin >> price; + prices.push_back(price); + } + + int result = solution.maxProfit(prices); + cout << "Maximum profit: " << result << endl; + + return 0; +}