/**
* 面试题63:股票的最大利润
* 题目:假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖股票一次可能获得的最大利润是多少?
* 例如,一只股票在某些时间节点的价格为{9,11,8,5,7,12,16,14}.如果我们能在价格为5的时候买入
* 并在价格为16的时候卖出,则能收获最大的利润11.
* 输入{9,11,8,5,7,12,16,14}
* 输出:11
* @author
* @create 2021-04-18 15:34
*/
public class Solution63 {
public static void main(String[] args) {
int[] arr = {9,11,8,5,7,12,16,14};
int profit = maxProfit(arr);
System.out.println(profit);
}
/**
* 记录买入的最小值与当前值的最大差
* @param prices
* @return
*/
public static int maxProfit(int[] prices){
if (prices == null || prices.length == 0){
return 0;
}
int minValue = prices[0];
int maxProfit =0;
for (int i = 1; i < prices.length; i++) {
if(prices[i] - minValue > maxProfit){
maxProfit = prices[i] - minValue;
}
if(prices[i] < minValue){
minValue = prices[i];
}
}
return maxProfit;
}
}