首页 > 代码库 > Leetcode:Best Time to Buy and Sell Stock

Leetcode:Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock1

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.

解析:题目要求只能最多完成一笔交易,也就是在n个数中选两个数,要求后一个数(卖出价钱)减去前一个数(买进价钱)的差值最大

解法一:

设dp[i]是[0,1,2...i]区间的最大利润,则该问题的一维动态规划方程如下

dp[i+1] = max{dp[i], prices[i+1] - minprices}  ,minprices是区间[0,1,2...,i]内的最低价格

我们要求解的最大利润 = max{dp[0], dp[1], dp[2], ..., dp[n-1]} 代码如下:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() == 0) return 0;
        int minPrices  = INT_MAX;
        int currProfit = INT_MIN;
        int maxProfits = INT_MIN;
        for (int i = 0; i < prices.size(); ++i) {
            minPrices = min(minPrices, prices.at(i));
            currProfit = prices.at(i) - minPrices;
            maxProfits = max(maxProfits, currProfit);
        }
        return maxProfits;
    }
};

 

解法二:

按照股票差价构成新数组 prices[1]-prices[0], prices[2]-prices[1], prices[3]-prices[2], ..., prices[n-1]-prices[n-2]。求新数组的最大子段和就是我们求得最大利润,假设最大子段和是从新数组第 i 到第 j 项,那么子段和= prices[j]-prices[j-1]+prices[j-1]-prices[j-2]+...+prices[i]-prices[i-1] = prices[j]-prices[i-1], 即prices[j]是最大价格,prices[i-1]是最小价格。

此解法需要注意:

a. 数组长度为1的情况

b. 最大字段和为负时的情况

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() == 0) return 0;
        if (prices.size() == 1) return 0;
        int maxSum = INT_MIN;
        int currSum = 0;
        for (int i = 0; i < prices.size() - 1; ++i) {
            currSum = max(currSum + prices.at(i+1) - prices.at(i), prices.at(i+1) - prices.at(i));
            maxSum  = max(maxSum, currSum);
        }
        return max(maxSum, 0);
    }
};

 

Best Time to Buy and Sell Stock2

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) {
        if (prices.size() == 0) return 0;
        if (prices.size() == 1) return 0;
        int maxSum = 0;
        for (int i = 0; i < prices.size() - 1; ++i) {
            if (prices.at(i+1) - prices.at(i) >= 0) {
                maxSum += (prices.at(i+1) - prices.at(i));
            }
        }
        return maxSum;
    }
};

 

Best Time to Buy and Sell Stock3