[LeetCode]Best Time to Buy and Sell Stock I/II/III

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.

设f(i)表示以第prices[i]卖出时所获的最大利润,则

f(i) = max{prices[i] - prices[k], 0<= k <= i}

     = prices[i] - min{prices[k], 0 <= k <= i}

那么最终所能获利的最大值为:

ans = max{f(i), 0 <= i < n}

恰好f(i)中的前i个的最小值可以在计算过程中顺便计算出来,因此代码如下:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int mp = 0, minv = INT_MAX;
        for (int i = 0; i < prices.size(); i++)
        {
            minv = min(minv, prices[i]);
            mp = max(mp, prices[i] - minv);
        }
        return mp;
    }
};

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

如果可以交易无数多次,那么只要有利润我就交易,这样能够保证赚的钱是最多的。

有利润就是卖时候的价钱比买得时候高,也就是说把所有的比前一天能多卖得钱累加起来即可。

class Solution {
public:
    int maxProfit(vector<int> &prices)
    {
        int ans = 0;
        for (int i = 1; i < prices.size(); i++)
            if (prices[i] - prices[i - 1] > 0)
                ans += prices[i] - prices[i - 1];
        return ans;
    }
};

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

如果只能交易两次,而且两次交易不可交叉,那么可以将本题二分。假设第一次交易在第k天前完成,第二次交易在第k天后完成,这样就变成了两个交易一次的问题。

设f(k)表示前k天所获最大利润,g(k)表示后n-k天所获最大利润,那么枚举一下k,所得的f(k)+g(k)的最大值即为答案。(k可为0,这允许了只进行一次交易的可能)

f(k) = max{ prices[i] - min{prices[j]}, 0 <= j <= i <= k }
g(k) = max{max{prices[j]} - prices[i], k <= i <= j <= n }

ans = max{f(k) + g(k)}

class Solution {
public:
    int maxProfit(vector<int> &prices)
    {
        int n = (int)prices.size();
        vector<int> f(n), g(n);
        int minv = INT_MAX, maxv = INT_MIN, ans = 0;
        for (int i = 0; i < n; i++)
        {
            minv = min(minv, prices[i]);
            f[i] = ans = max(ans, prices[i] - minv);
        }
        ans = 0;
        for (int i = n - 1; i >= 0; i--)
        {
            maxv = max(maxv, prices[i]);
            g[i] = ans = max(ans, maxv - prices[i]);
        }
        
        ans = 0;
        for (int k = 0; k < n; k++)
            ans = max(ans, f[k] + g[k]);
        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值