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

来源:互联网 发布:mac系统恢复出厂设置 编辑:程序博客网 时间:2024/06/14 01:30

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,也就是原题中的最大差值!!

参考

  • leetcode 121

  • wiki

阅读全文
0 0
原创粉丝点击