C++面试题(50)------股票的最大利润

  • 操作系统:ubuntu22.04
  • IDE:Visual Studio Code
  • 编程语言:C++11

题目描述

假设把某股票的价格按照时间先后顺序存储在数组中,
请你计算一次交易中能获取的最大利润(卖出价 - 买入价)。

示例:

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


解释:
    在价格为 1 的时候买入,在价格为 6 的时候卖出,利润最大 = 6-1 = 5
输入: [7,6,4,3,1]
输出: 0

解释:
    没有上涨趋势,无法获利。

解法思路:一次遍历 + 贪心思想

这是一道经典的动态规划 / 贪心算法题。

我们只需要遍历一次数组,在每个位置记录当前的最小买入价格,并计算当天卖出可能获得的最大利润。

代码


#include 
#include 

using namespace std;

class Solution {
public:
    int maxProfit( vector< int >& prices )
    {
        if ( prices.empty() )
            return 0;

        int minPrice  = prices[ 0 ];
        int maxProfit = 0;

        for ( int i = 1; i < prices.size(); ++i )
        {
            // 更新最低买入价
            if ( prices[ i ] < minPrice )
                minPrice = prices[ i ];
            else
                // 计算当前卖出利润
                maxProfit = max( maxProfit, prices[ i ] - minPrice );
        }

        return maxProfit;
    }
};

int main()
{
    Solution s;
    vector<int> prices = { 7, 1, 5, 3, 6, 4 };
    cout << s.maxProfit( prices ) << endl;
    prices = { 7, 6, 5, 4, 3, 3 };
    cout << s.maxProfit( prices ) << endl;
    return 0;
}

运行结果

5
0

你可能感兴趣的:(c++,c++,开发语言)