Best Time to Buy/Sell Stock I — Single Transaction
Advertisement
Problem
Choose one day to buy and a later day to sell. Maximize profit (or 0).
Solutions
Python
class Solution:
def maxProfit(self, prices: list[int]) -> int:
min_p=float('inf'); best=0
for p in prices:
min_p=min(min_p,p); best=max(best,p-min_p)
return best
C++
class Solution {
public:
int maxProfit(vector<int>& p){
int mn=INT_MAX,best=0;
for(int x:p){mn=min(mn,x);best=max(best,x-mn);}
return best;
}
};
Java
class Solution {
public int maxProfit(int[] p){
int mn=Integer.MAX_VALUE,best=0;
for(int x:p){mn=Math.min(mn,x);best=Math.max(best,x-mn);}
return best;
}
}
Complexity
- Time: O(n) | Space: O(1)
Advertisement