把题目中的稀世珍品 换成 股票的概念就很好理解了,你若知道明天会涨,哪今天买入,明天卖出。明天的时候,你若知道后天会涨,则明天也买入,后台卖出…依次类推,必然获得最大收益
/**
* HW二面 面试官 出的题目
*/
public class MainTest {
// 假设你是一名古董商人,近期市场上出现了一件稀世珍品,
/**
*
* 一只股票,你能预知它今后N天每一天的市场价格(给定一个数组,下标为第i天,值为第i天价格),
* 你希望通过买卖来赚取利润,请计算下你能获得的最大利润。
*/
public int getMaxProfit(int[] prices) {
int last = prices[0];
int profit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > last) {
profit += prices[i] - last;
}
last = prices[i];
}
return profit;
}
@Test
public void testExample1() {
int[] arr = new int[]{1, 3, 1, 10, 100, 1000};
Assert.assertEquals(1001, getMaxProfit(arr));
arr = new int[]{2, 4, 5, 2, 9, 7, 8, 10, 8};
Assert.assertEquals(13, getMaxProfit(arr));
}
}