121. Best Time to Buy and Sell Stock
You get an array of prices where prices[i] is the price of the given stock on that day.
You want to maximize your profit by choosing a single day to buy one stock and choose another day in the future to sell that stock.
Return the maximum profit you can make from this transaction. If you can't make any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed as you must buy before selling.
Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no trades are made and maximum profit = 0.
Limitations:
1 <= prices.length <= 105
0 <= prices[i] <= 104
Solution
class Solution {
public:
int maxProfit(vector& prices) {
int n = prices.size();
int maxi =0,mini = INT_MAX;
for(int i=0; i
Comments
Post a Comment