import java.util.*;
public class Solution {
// 使用贪心算法
public int maxProfit (int[] prices) {
// 初始化
int minPrice = Integer.MAX_VALUE; // 实时记录历史最低价格
int maxProfit = 0;
// 遍历数组
for (int price : prices) {
// 更新最低价格
if (price < minPrice) {
minPrice = price;
} else {
// 更新最大利润
maxProfit = (price - minPrice) > maxProfit ? (price - minPrice) : maxProfit;
}
}
// 遍历结束,返回最大利润
return maxProfit;
}
}



京公网安备 11010502036488号