Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- /*
- QUESTION - https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/
- */
- int getMaxProfitInfiniteTransaction(vector < int > & prices) {
- int totalProfit = 0, minIdx = -1;
- for(int i = 0; i < prices.size(); i++){
- //form a minimum OR capture a better minimum to buy
- if(minIdx == -1 || prices[i] < prices[minIdx]){
- minIdx = i;
- }
- //capture the best day to sell
- else{
- // if the next day has lower price than the current day, capture the buy - sell pair and make profit
- if(i != prices.size() - 1 && prices[i + 1] < prices[i]){
- totalProfit += (prices[i] - prices[minIdx]);
- //reset the minIndex/buy day to -1, as we have already captured the profit for this buy, as we made a complete transaction by selling the share today
- minIdx = -1;
- }
- //handling for last index, capture only if a buy exists.
- else if(i == prices.size() - 1){
- if(minIdx != -1){
- totalProfit += (prices[i] - prices[minIdx]);
- }
- }
- }
- }
- return totalProfit;
- }
- int main() {
- // your code goes here
- int n;
- cin >> n;
- vector < int > prices(n);
- for (int i = 0; i < n; i++) {
- cin >> prices[i];
- }
- cout << getMaxProfitInfiniteTransaction(prices) << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement