122Best Time to Buy and Sell Stock II

来源:互联网 发布:淘宝app官方下载 编辑:程序博客网 时间:2024/06/06 00:15

题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

题目:

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.

解题思路:
这道题考点依然是动态规划,感觉已经连做好几题动态规划了。。。
自己的思路是全局和局部不断更新的过程:
1. 维护一个全局最大值和局部最大值。二者都初始化为数组最后一个元素。
2. 从后向前遍历数组,若当前元素 a[i] 比之前 a[i + 1]小时,继续向前遍历数组。
3. 否则,即 a[i] > a[i + 1] 时,说明 a[i + 1] 到局部最大值有最大的利润,局部最大利润的递推公式为:
localProfit = localProfit + localMax - a[i + 1]
4. 全局最大值到 a[i + 1],也有可能产生最大利润,所以全局最大利润(此利润并非最终结果的那个全局最大利润,而是全局最大值与当前最小值的差)的递推公式为:
globalProfit = max(globalProfit, globalMax - a[i + 1])
5. 与此同时, a[i] 成为当前局部最大值;如果 a[i] > 全局最大值,也应当更新全局最大值。
6. 注意,当遍历到数组第一个元素时应该特别进行处理。

这种处理方式稍显复杂。看了大神的做法,才发现确实是想复杂了。大神思路如下:
这题与 121 Best Time to Buy and Sell Stock 不同之处在于,可以交易无限多次(当然我们知道交易不会超过 n - 1 次,也就是每天都进行先卖然后买)。
1. 既然交易次数没有限定,可以看出我们只要对于每次两天差价大于 0 的都进行交易,就可以得到最大利润。
2. 因此算法其实就是累加所有大于 0 的差价既可以了,非常简单。
3. 如此只需要一次扫描就可以了,时间复杂度是 O(n),空间上只需要 O(1) 存一个累加结果即可。
附上大神参考链接:http://blog.csdn.net/linhuanmars/article/details/23164149

代码实现:
大神的代码:

public class Solution {    public int maxProfit(int[] prices) {          if(prices == null || prices.length==0)              return 0;          int res = 0;          for(int i=0;i<prices.length-1;i++)          {              int diff = prices[i+1]-prices[i];              if(diff>0)                  res += diff;          }          return res;      }}
198 / 198 test cases passed.Status: AcceptedRuntime: 2 ms

自己的代码:

public class Solution {    public int maxProfit(int[] prices) {        if(prices == null || prices.length == 0)            return 0;        int len = prices.length;        int localMax = prices[len - 1];        int globalMax = prices[len - 1];        int localProfit = 0;        int globalProfit = 0;        int profit = 0;        for(int i = len - 2; i >= 0; i --) {            if(i > 0 && prices[i] <= prices[i + 1])                continue;            if(i == 0 && prices[i] <= prices[i + 1]) {                localProfit = localMax - prices[i]  + localProfit;                globalProfit = Math.max(globalMax - prices[i], globalProfit);            } else {                localProfit = localMax - prices[i + 1]  + localProfit;                globalProfit = Math.max(globalMax - prices[i + 1], globalProfit);                localMax = prices[i];                globalMax = Math.max(globalMax,prices[i]);            }            profit = Math.max(localProfit, globalProfit);        }        return profit;    }}
198 / 198 test cases passed.Status: AcceptedRuntime: 4 ms
0 0
原创粉丝点击