121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

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

同53题.
The maximum (minimum) subarray problem. 用到(DP).
这题是重点:
就是序列从A[0]开始计算, 不符合条件就清0, 从断处继续计算. 好处是 (O(n)) time 就可以处理, 牛逼的不行不行的.
(O(n)) time, (O(1)) space.

照葫芦画瓢代码:

//是个 最大子序列问题 相对应的 有最小子序列问题
//Kadane’s algorithm uses the dynamic programming approach
//to find the maximum (minimum) subarray
int maxProfit(vector<int>& A) {
    int i = 1, profit = 0, temp = 0, p = 0;
    while (i < A.size()) {
        temp = A[i] - A[i - 1];
        p = max(0, p += temp); //难点在这,p要和temp累积,小于0则清0
        profit = max(p, profit); //profit记录累积过程中的最大收益值
        i++;
    }
    return profit;
}

int max(int a, int b) {
    return a > b ? a : b;
}

更牛逼的代码:
//TODO 还没看呢

int maxProfit(vector<int>& prices) {
    int mini = INT_MAX;
    int pro = 0;

    for (int i = 0; i < prices.size(); i++) {
        mini = min(prices[i], mini);
        pro = max(pro, prices[i] - mini);
    }
    return pro;
}
原文地址:https://www.cnblogs.com/ZhongliangXiang/p/7357005.html