Best Time to Buy and Sell Stock
1 min readJun 6, 2019
Question: Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
You may view the full question here.
Approach 1: Here is the first approach that comes to mind —
//Approach 1:
//Runtime: 1ms
//Memory usage: 38MBclass Solution {
public int maxProfit(int[] prices) {
int min = 0;
int minInd = 0;
if(prices.length>0){
min = prices[0];
minInd = 0;
}
int diff = 0;
for(int i = 1; i<prices.length; i++){
if(prices[i]<min){
min = prices[i];
minInd = i;
} else {
diff = Math.max(diff, prices[i]-min);
}
}
return diff;
}
}
Find more posts here.
Cheers & Chao!