Best Time to Buy and Sell Stock解题

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

<code>Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
/<code>

Example 2:

<code>Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0./<code>

题目大概意思就是,股票的价格变化如数组中所示,找出最大利润。

我们来归纳一下,[7,1,5,3,6,4]

以4卖出的时候,我们把4前面的数都比较一次,1的价格是最合适买入的,利润为3;

以6卖出的时候,我们把6前面的数都比较一次,1的价格是最合适买入的,利润为5;

......

最后我们求出最大利润为5。

这样比较的次数有些多,我们换一种思路,

3之后最大的数为6,利润为3;

5之后最大的数为6,利润为1;

1之后最大的数为6,利润为5;

......

最后我们求出最大利润为5,所以我们倒过来遍历,把最大值计算出来即可。

贴出代码

<code>  public static int maxProfit(int[] prices) {

int maxVal = 0;
int maxSum = 0;
for (int i = prices.length - 1; i >= 0 ; i--) {
maxSum = Math.max(maxVal - prices[i], maxSum);
maxVal = Math.max(maxVal, prices[i]);
}

return maxSum;
}/<code>


分享到:


相關文章: