题目:股票的最大利润
求买卖股票一次能获得的最大利润。例如,输入{9,11,8,5,7,12,16,14},5的时候买入,16的时候卖出,则能获得最大利润11。
思路:
这道题只需要遍历一次数组,用一个变量buy记录遍历过数中的最小值,然后每次计算当前值和这个最小值之间的差值最为利润res,然后每次选较大的利润来更新。当遍历完成后当前利润即为所求。
基于以上思路,java参考代码如下:
public class MaximalProfit {
public static int maxDiff(int[] prices){
if(prices==null||prices.length<2)
return 0;
int buy=Integer.MAX_VALUE,res=Integer.MIN_VALUE;//将buy和res初始化为最大值和最小值,有益于后面的比较
for(int price:prices) {
res=Math.max(res,price-buy);
buy=Math.min(buy, price);
//res=Math.max(res,price-buy);//res和buy的顺序相当重要
}
return res;
}
public static void main(String[] args){
int[] data1 = new int[]{9,11,8,5,7,12,16,14};
int[] data2 = new int[]{9,8,7};
System.out.println(maxDiff(data1)); //11
System.out.println(maxDiff(data2)); //-1
}
}
测试用例:
a.功能测试(存储股票价格的数组无序、单调递增、单调递减)。
b.边界值测试(存储股票价格的数组中只有两个数字)。
c.特殊输入测试(指向数组的指针为nullptr)。