话不多说,直接上代码。
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[] = new int[5];
Scanner in = new Scanner(System.in);
for(int i = 0; i < 5; i++) {
array[i] = in.nextInt();
}
int gap = maxProfit(array);
System.out.print(gap);
}
// 股票交易最佳时机,采用一次遍历
// 思路:假设你从一周中选择最低价格那天买入,当天卖出,那么在最低点买入,最高点卖出
public static int maxProfit(int[] prices) {
int maxProfit = 0; // 最大收益
int buy = Integer.MAX_VALUE; // 当天购买的价格
for(int i = 0; i < prices.length; i++){
if(prices[i] < buy){
buy = prices[i];
}else if(prices[i] - buy > maxProfit){
maxProfit = prices[i] - buy;
}
}
return maxProfit;
}
}
测试结果,上图: