一、题目描述
二、解法
package question3;
/**
* @description: 暴力法求解
* @author: hyr
* @time: 2020/5/9 9:08
*/
public class Solution {
public static void main(String[] args) {
int prices[] = {7, 1, 5, 3, 6, 4};
System.out.println("最大利润为:" + maxProfit(prices));
System.out.println("最大利润为:" + maxProfit(prices));
}
/**
* 挑选出所有的组合,用 if 条件过滤。
*/
public static int maxProfit(int[] prices) {
int length = prices.length;
int tempProfit;
int max = 0;
for (int i = 0; i < length - 1; i++) {
for (int j = i + 1; j < length; j++) {
if (prices[i] >= prices[j]){
continue;
}
tempProfit = prices[j] - prices[i];
if (tempProfit > max){
max = tempProfit;
}
}
}
return max;
}
}
运行结果:
最大利润为:5