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.
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2) return 0;
int buySoFar, sellSoFar, profit, buyCur;
sellSoFar=profit=0;
buySoFar=prices[0];
buyCur=-1;
//4,7,1,2,11
for(int i=1; i<prices.length; i++){
if(buyCur==-1){
if(prices[i]>buySoFar && prices[i]-buySoFar>profit)
{
sellSoFar=prices[i];
profit=sellSoFar-buySoFar;
}
if(prices[i]<buySoFar)
buyCur=prices[i];
}
else{
if(prices[i]>buyCur && prices[i]-buyCur>profit)
{
sellSoFar=prices[i];
profit=sellSoFar-buyCur;
buySoFar=buyCur;
}
if(prices[i]<buyCur)
buyCur=prices[i];
}
}
return profit;
}
}上面的解法其实是把问题想复杂了
当我们得到一个新的最小值时,直接将其设为买入价(buySoFar)即可,后面判断新的卖出价和这个买入价的差值是否大于已经存储的profit值即可。
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<2 || prices==null) return 0;
int buySoFar, profit;
profit=0;
buySoFar=prices[0];
//3,10,1,6
for(int i=1; i<prices.length; i++){
if(prices[i]<buySoFar)
buySoFar=prices[i];
else if(prices[i]-buySoFar>profit)
profit=prices[i]-buySoFar;
}
return profit;
}
}
本文介绍了一种寻找股票交易中最大利润的算法。该算法通过一次遍历价格数组,跟踪最低购买价格并更新最大利润来实现。适用于仅允许进行一次买卖的情况。

被折叠的 条评论
为什么被折叠?



