Professional Documents
Culture Documents
A 5
A 5
You want to maximize your pro t by choosing a single day to buy one stock and choosing
a di erent day in the future to sell that stock.
Return the maximum pro t you can achieve from this transaction. If you cannot achieve any pro t,
return 0.
Example 1:
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), pro t = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you
sell.
Example 2:
Output: 0
Explanation: In this case, no transactions are done and the max pro t = 0.
Constraints:
I will share two approaches here to solve the above problem-one is the Brute Force Approach &
the Optimized Approach.
In this for every element traverse the rest part of the array and nd the pro t using prices[j]-
prices[i]; and keep comparing to nd the maximum pro t.
Since for every element you will have to traverse the rest part of the array, the time complexity will
be O(n*n), but the space complexity will remain as O(1).
Optimal Approach
In this approach, we will do a linear traversal, our approach would be to nd the smallest element
in the left half and nd the largest element in the other half. Simultaneously I will keep comparing
to nd the maximum pro t.
class Solution {
public:
int max_Pro t = 0;
for(int i=0;i<prices.size();i++)
min_price = min(min_price,prices[i]);
return max_Pro t;
};
min_price = INT_MAX
max_Pro t = 0
min_price = min(INT_MAX,7) = 7
min_price = min(7,1) = 1
min_price = min(1,5) = 1
min_price = min(1,3) = 1
min_price = min(1,6) = 1
fi
ff
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
fi
max_Pro t = max(4,6-1) = max(4,5) = 5
min_price = min(1,4) = 1
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
https://www.youtube.com/watch?
v=eMSfBgbiEjk&list=PLgUwDviBIf0rPG3Ictpu74YWBQ1CaBkm2&index=12
Hope you have understood the approach above. In case of any queries feel free to comment
below. Till then keep coding and keep learning, Remember consistency is the key!!!
Since you enjoyed reading my blog , why not buy me a co ee and supoort my work here!! https://
www.buymeaco ee.com/sukanyabharati ☕
Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to
our newsletter tinyletter.com/TheLeanProgrammer
fi
fi
ff
fi
fi
ff