股票的最大利润-63
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖 一次 该股票可能获得的利润是多少?
例如一只股票在某些时间节点的价格为 [9, 11, 8, 5, 7, 12, 16, 14]。
如果我们能在价格为5的时候买入并在价格为 16 时卖出,则能收获最大的利润11。
样例
输入:[9, 11, 8, 5, 7, 12, 16, 14]
输出:11
思路:
遍历每一个数字,并保存之前最小的数字,两者差最大即为最大利润。
class Solution {
public int maxDiff(int[] nums) {
int min = Integer.MAX_VALUE, max = 0;
for (int num : nums) {
if (num < min) min = num;
max = Math.max(max, num - min);
}
return max;
}
}