天天看点

LeetCode_Array_121. Best Time to Buy and Sell Stock买卖股票的最佳时机(C++)1,题目描述2,解题思路3,AC代码4,解题过程

目录

1,题目描述

英文描述

中文描述

2,解题思路

基本思想

3,AC代码

4,解题过程

第一博

第二搏

1,题目描述

英文描述

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]

Output: 5

Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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

Explanation: In this case, no transaction is done, i.e. max profit = 0.

中文描述

给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。

如果你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润。

注意:你不能在买入股票前卖出股票。

示例 1:

输入: [7,1,5,3,6,4]

输出: 5

解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。

     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。

示例 2:

输入: [7,6,4,3,1]

输出: 0

解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

2,解题思路

参考@力扣官方题解【121. 买卖股票的最佳时机】

基本思想

  • minPrice维护当前遍历到的最小值(最低点);
  • 每到一个新的点,更新一次minPrice,并且利用ans = max(ans, prices[i] - minPrice) 更新ans;

就是这么简单。

3,AC代码

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

4,解题过程

第一博

O(N^2)的算法肯定都知道,双重遍历,每对合理的位置都判断一下。但是不用想,稳稳超时。

于是换了一种思路,声明两个数组in和out分别记录到位置 i(包括i)之前/之后的最小值/最大值,然后再次遍历一边数组,将对应位置的值相减,更新结果;

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        vector<int> in(prices.size());              // 记录买入时各位置之前的最低价格
        vector<int> out(prices.size());             // 记录卖出时各位值之后的最高价格
        if(prices.size() == 0) return 0;            // 可能出现数组元素为空的情况
        int ans = -1;                               // 初始为-1 用来标识无满足条件的解
        in[0] = prices[0];
        for(int i = 1; i < prices.size(); ++i)      // 从前往后 更新各位置之前的最低价格
            in[i] = min(in[i - 1], prices[i]);
        out[prices.size() - 1] = prices.back();
        for(int i = prices.size() - 2; i >= 0; --i) // 从后往前 更新各位置之后的最高价格
            out[i] = max(out[i + 1], prices[i]);
        for(int i = 0; i < prices.size(); i++)      // 获得最终结果
            ans = max(ans, out[i] - in[i]);
        if(ans < 0) return 0;
        return ans;
    }
};
           
LeetCode_Array_121. Best Time to Buy and Sell Stock买卖股票的最佳时机(C++)1,题目描述2,解题思路3,AC代码4,解题过程

第二搏

看了官方题解后,感觉自己┗( T﹏T )┛

为啥要来回遍历两次数组呢?维持一个当前最小值minPrice,配合当前值prices[i]来更新ans不香吗?

LeetCode_Array_121. Best Time to Buy and Sell Stock买卖股票的最佳时机(C++)1,题目描述2,解题思路3,AC代码4,解题过程