把某股票的价格按照先后顺序存储在数组里,请问买卖该股票一次可能获得的最大利润是多少?例如,一只股票在某些事件结点的价格为{9, 11, 8, 5, 7, 12, 16, 14}。如果我们能在价格为5的时候买入并在价格为16时卖出,则能收获最大的利润11.
简单思路就是类似冒泡排序的方法,暴力遍历数组,找到所有的可能值,然后找最小。
进阶思路就是,保存数组中第 i 个数组前面所有数字中最小的那一个,然后与数组第 i 个数字相减。这样就算出了第i个数字对应的最大利润。这样遍历数组时间复杂度就是O(n)。
代码如下:
import org.junit.Test;
public class Solution{
public int findProfit(int[] num){
if (num == null || num.length == 0) {
return -1;
}
int min = num[0];
int profit = num[1] - num[0];
for (int i = 1; i < num.length; i++){
if (num[i] < min) {
min = num[i];
}
if (num[i] - min > profit) {
profit = num[i] - min;
}
}
return profit;
}
@Test
public void test(){
int[] num = {9, 11, 8, 5, 7, 12, 16, 14};
System.out.println(findProfit(num));
}
}