题目描述
已知一个数组,第i个元素表示第i天股票的价格,你只能进行一次交易(买卖各一次),设计算法找出最大收益
测试样例
Input: [7, 1, 5, 3, 6, 4]
Output: 5
最大收益 = 6-1 = 5
Input: [7, 6, 4, 3, 1]
Output: 0
最大收益为0
解决方案:
public static int getMaxProfit(int[] num) {
int profit = 0;
int minBuy = Integer.MAX_VALUE;
for (int i = 0; i < num.length; i++) {
int e = num[i];
if (e < minBuy) {
minBuy = e;
}
if (e - minBuy > profit) {
profit = e - minBuy;
}
}
return profit;
}