LeetCode - BestTimetoBuyandSellStockI

来源:互联网 发布:流动商贩全国数据 编辑:程序博客网 时间:2024/06/17 15:01

/**

 * 问:给出了一个股票的价格数组,求买入再卖出的最大收益。

 * 解:

 * 1、股票的卖出必定在买入之后,所以我们求的不是数组的最大差值。

 * 2、通过O(n*n)很容易求出一个数和其后面的数的差值的最大值,但显然不是好的算法。

 * 3、有一个巧妙的方法是创建一个数组,记录对应位置元素后面的最大值,然后将该数组

 *     减原数组,得出一个最大差值数组,遍历该最大差值数组即可得出最大收益。

 * 4、得到每个元素后面所有元素的最大值,也有一个巧妙的方法:从后往前遍历。

 */

public class BestTimetoBuyandSellStockI {

public int maxProfit(int[] prices) {

int length = prices.length;

int[] maxValues = new int[length]; // 存放每个位置后面的最大元素

maxValues[length-1] = 0; // 尾元素后面的最大值为0

int tempMax = prices[length-1]; // 最大值初始化为尾元素

// 从倒数第二个元素往前来确定每个元素后面所有元素的最大值

for (int i=length-2; i>=0; i--) {

if (tempMax < prices[i]) // 始终保持tempMax为目前的最大值

tempMax = prices[i];

maxValues[i] = tempMax; // 目前的最大值即为该位置元素后面的最大元素

}

// 求出两个数组对应位置之间的最大差值

int result = 0;

for (int i=0; i<length; i++) {

if (result < (maxValues[i] - prices[i])) 

result = maxValues[i] - prices[i];

}

return result;

}

public static void main(String[] args) {

int[] prices = {9, 1, 2, 8, 3, 7};

System.out.println("最大收益:" + new BestTimetoBuyandSellStock().maxProfit(prices));

}

}
0 0