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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
只允许进行交易一次,也就是先买一次然后再卖一次。 所以在买的时候应该找最低点,卖的时候找最高点,但是买必须在卖之前。
public class BestTimetoBuyandSellStock {
public int maxProfit(
int[] prices) {
if(prices==
null || prices.length==
0) {
return 0;
}
int min = Integer.MAX_VALUE;
int profit =
0;
for(
int i: prices) {
min = i<min ? i:min;
profit = (i-min)>profit ?i-min:profit;
}
return profit;
}
}
转载请注明原文地址: https://ju.6miu.com/read-10523.html