题目描述
// 63. 股票的最大利润
// 力扣
// 假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该
// 股票一次可能获得的最大利润是多少?
题解
////////////////////////////// 贪心算法 ////////////////////////////////
// 力扣
// 初始化min
// 执行用时:2 ms, 在所有 Java 提交中击败了66.58%的用户
// 内存消耗:38.2 MB, 在所有 Java 提交中击败了71.67%的用户
class Solution {
public int maxProfit(int[] prices) {
if (prices.length == null || prices.length == 0)
return 0;
int minPrice = prices[0];
int profit = Integer.MIN_VALUE;
for (int p : prices) {
minPrice = Math.min(p, minPrice);
profit = Math.max(profit, (p - minPrice));
}
return profit;
}
}