话不多说,直接上代码。
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
// 这里可以模仿输入一周五天的股价
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 gap = 0;
int buy = 0;
for(int i = 0; i < prices.length-1; i++){
int max = 0;
buy = prices[i];
for(int j = i+1; j < prices.length; j++){
if(prices[j] > max){
max = prices[j];
}
}
gap = Math.max(gap, max - buy);
}
return gap;
}
}
上结果看看: