</> ᴍᴜᴋᴇsʜ </>
Best time to buy /sell any stock
public class buysell {
public static int buySellStock(int prices[]) {
int MaxProfit = 0;
int buyPrice = Integer.MAX_VALUE;
for (int index = 0; index < prices.length; index++) {
if (buyPrice < prices[index]) {
int profit = prices[index] - buyPrice;
MaxProfit = Math.max(profit, MaxProfit);
} else {
buyPrice = prices[index];
}
}
return MaxProfit;
}
public static void main(String[] args) {
int prices[] = { 7, 1, 5, 6, 2, 3 };
System.out.println(buySellStock(prices));
}
}
Output:
5
5 · 3.3K ·