leetcode 121. Best Time to Buy and Sell Stock | 最大差值和最大子序列关系

Descrpition

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.

My solution

/// 自己写的code复杂度n2,运行时间太长(虽然是一次)
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int minp = 100000, maxp = -1, res = 0, temp;
        for (int i = 0; i < prices.size(); i++) {
            if (prices[i] < minp) {
                minp = prices[i];
                for (int j = i; j < prices.size(); j++) {
                    maxp = prices[j] > maxp ? prices[j] : maxp;
                }
            }
            temp = maxp - minp;
            res = temp > res ? temp : res;
            maxp=-1;
        }
        return res;
    }
};

Discuss

自己算法复杂度较高,通过查看Discuss网友答案,可简化为O(n):

方案1:

  int maxProfit(vector<int> &prices) {
    int maxPro = 0;
    int minPrice = INT_MAX;
    for(int i = 0; i < prices.size(); i++){
        minPrice = min(minPrice, prices[i]);
        maxPro = max(maxPro, prices[i] - minPrice);
    }
    return maxPro;
}

简化的主要原因是用maxpro和minPrice变量存储历史最优解,一次遍历之后即可输出此过程中的最优解.而我的方案中的大量工作在精确最优解的位置,故更为繁琐.
事实上这种记录最优时刻的方法是动态规划思想.

方案2:

Kadane’s Algorithm - Since no one has mentioned about this so far :) (In case if interviewer twists the input)
The logic to solve this problem is same as “max subarray problem” using Kadane’s Algorithm. Since no body has mentioned this so far, I thought it’s a good thing for everybody to know.

All the straight forward solution should work, but if the interviewer twists the question slightly by giving the difference array of prices, Ex: for {1, 7, 4, 11}, if he gives {0, 6, -3, 7}, you might end up being confused.

Here, the logic is to calculate the difference (maxCur += prices[i] - prices[i-1]) of the original array, and find a contiguous subarray giving maximum profit. If the difference falls below 0, reset it to zero.

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;
}

注意到 {1, 7, 4, 11} -> {0, 6, -3, 7}的转化,实际上是做的 anan1 , 即 {0,a0+a1,a1+a2,a2+a3} ,”连续最大和”即是 (a0+a1)+(a1+a2)+(a2+a3)=a3a1 ,也就是原题中的最大差值!!

参考

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值