-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
solution(cpp): 122. Best Time to Buy and Sell Stock II
122. Best Time to Buy and Sell Stock II - C++
- Loading branch information
Showing
1 changed file
with
46 additions
and
0 deletions.
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
Easy/122. Best Time to Buy and Sell Stock II/122. Best Time to Buy and Sell Stock II.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |