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 (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:###
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:###
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
给定一个序列的股票价格,允许一次交易,找到出最大的盈利。其中要求是需要先买(先持有)才能再卖。
说白了就是给定一个整数数组,数组后面的元素减去前面的数组元素,差值最大的是多少。
先举一个例子 [1,2,3,4,5,6]
,最大的差值为5, 计算的过程为后面的元素减去前面一个元素的和,即sum([0,1,1,1,1,1]),可以看出最大的差值是前面差值的累积。再看例子[7,1,5,3,6,4]
,后面元素和前面元素的差值为[0,-6,,4,-2,3,-2]
,tmp += prices[i] - prices[i-1]
,如果tmp小于0,则重置为0.
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
int tmp = 0;
for(int i = 0; i < prices.length - 1; i++)
{
tmp = Math.max(0,tmp += prices[i+1]-prices[i]);
max = Math.max(tmp,max);
}
return max;
}
}