Skip to content

Commit

Permalink
solution(cpp): 122. Best Time to Buy and Sell Stock II
Browse files Browse the repository at this point in the history
122. Best Time to Buy and Sell Stock II
- C++
  • Loading branch information
godkingjay authored Oct 14, 2023
2 parents 03ef186 + f4a40c6 commit 4be8a8e
Showing 1 changed file with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
int maxProfit(vector<int>& 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<int> 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;
}

0 comments on commit 4be8a8e

Please sign in to comment.