Closed PisecesPeng closed 3 years ago
private static int func(int[] ints) {
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
int result = 0;
for (int i = 0; i < ints.length; i++) {
int v = ints[i];
// 判定最大最小值
if (min > v) {
min = v;
max = min; // 最小值刷新时, 重制最大值
} else if (max < v) {
max = v;
result = (result < (max - min)) ? (max - min) : result; // 最大值刷新时, 重新判断最大利润
}
}
return result;
}
public static int func(int prices[]) {
int maxprofit = 0;
for (int i = 0; i < prices.length - 1; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
if (profit > maxprofit) {
maxprofit = profit;
}
}
}
return maxprofit;
}
public static int func(int prices[]) {
int minprice = Integer.MAX_VALUE;
int maxprofit = 0;
for (int i = 0; i < prices.length; i++) {
if (prices[i] < minprice) {
minprice = prices[i];
} else if (prices[i] - minprice > maxprofit) {
maxprofit = prices[i] - minprice;
}
}
return maxprofit;
}
买卖股票的最佳时期
给定一个数组, 它的第
i
个元素是一支给定股票第i
天的价格.如果你最多只允许完成一笔交易(即买入和卖出一支股票一次), 设计一个算法来计算你所能获取的最大利润.
注意: 你不能在买入股票前卖出股票.
题目地址: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/