121.Best Time to Buy and Sell Stock

     今天刷Leetcode,遇到这样一个问题。

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.


       转换一下,问题变成求数组中的前后两个数t1和t2,它们差值最大且t1<t2。

       我的思路是这样的,从后往前,寻找当前子串的最大值,并计算最大值与当前价值prices[i]的差值,返回最大的差值。代码实现如下:

public int maxProfit(int[] prices) {
        if(prices.length==0||prices.length==1) return 0;
int length=prices.length;
int maxPro=0;
int maxSale=prices[length-1];
for (int i = length-2; i >=0; i--) {
if(prices[i]>maxSale)
maxSale=prices[i];
if(maxSale-prices[i]>maxPro)
maxPro=maxSale-prices[i];

}

return maxPro;

    }

        提交成功以后发现这题的其他解法,用了Kadane's Algorithm,方法如下:

 public int maxProfit(int[] prices) {
        int maxCur = 0, maxSoFar = 0;
        for(int i = 1; i < prices.length; i++) {
            maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
            maxSoFar = Math.max(maxCur, maxSoFar);
        }
        return maxSoFar;
    }

     这个方法借鉴了Kadane算法的思想。  

     Kadane算法具体详情可以参照这篇博客:

      http://www.linkedin.com/pulse/kadanes-algorithm-mustafa-bedir-tapkan

        这里只贴一张图:


     这个方法跟动态规划类似,用于寻找具有最大和的子数列,基于两个前提:

Kadane says that in each iteration we have only two options to get the max subarray:

  1. It can be only itself
  2. It can be itself combined with the maximum subarray that previous index has.

   伪码如下:

kadane(Array){
     
  generalMaximum = currentMaximum = Array[0]
   
  for (i = 1 until n) {
    
    currentMaximum = maximum of(Array[i], currentMaximum + Array[i]);
    if(currentMaximum >= generalMaximum) generalMaximum = currentMaximum;
  }
  
  return generalMaximum;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值