买卖股票的最佳时机

290 阅读3分钟

买卖股票的最佳时机

给定一个长度为 N 的数组prices[],代表不同日期的股票价格,任务是在最多允许一笔交易的情况下,通过在不同日期买卖股票来找到可能的最大利润。

注意:股票必须先买后卖。

例子:

输入:价格[] = {7, 1, 5, 3, 6, 4}
输出:5
解释:
股票最低价出现在第2天,即价格=1。从第2天开始,股票最高价出现在第5天,即价格=6。
因此,最大可能利润 = 6 – 1 = 5。

输入:价格[] = {7, 6, 4, 3, 1}
输出:0
说明:由于数组是按降序排列的,因此不存在解决该问题的可能方法。

使用贪心法:

为了利润最大化,我们必须最小化成本价格,最大化销售价格。因此,在每一步中,我们都会跟踪迄今为止遇到的股票最低买入价。如果股票的当前价格低于之前的买入价格,那么我们将更新买入价格,否则如果股票的当前价格大于之前的买入价格,那么我们可以在此价格卖出以获得一些利润。迭代整个数组后,返回最大利润。

按照以下步骤来实现上述想法:

  • 声明一个 buy 变量来存储迄今为止遇到的最低股价,并声明 max_profit 来存储最大利润。
  • 将 buy 变量初始化为价格数组的第一个元素。
  • 迭代数组并检查当前价格是否低于购买价格。
    • 如果当前价格小于买入价,则在第 i 天买入。
    • 如果当前价格大于买入价格,则从中获利并最大化 max_profit。
  • 最后,返回max_profit。

下面是上述方法的实现:

C++

// C++ code for the above approach
#include <iostream>
using namespace std;
 
int maxProfit(int prices[], int n)
{
    int buy = prices[0], max_profit = 0;
    for (int i = 1; i < n; i++) {
 
        // Checking for lower buy value
        if (buy > prices[i])
            buy = prices[i];
 
        // Checking for higher profit
        else if (prices[i] - buy > max_profit)
            max_profit = prices[i] - buy;
    }
    return max_profit;
}
 
// Driver Code
int main()
{
    int prices[] = { 7, 1, 5, 6, 4 };
    int n = sizeof(prices) / sizeof(prices[0]);
    int max_profit = maxProfit(prices, n);
    cout << max_profit << endl;
    return 0;
}

Java

// Java code for the above approach
class GFG {
    static int maxProfit(int prices[], int n)
    {
        int buy = prices[0], max_profit = 0;
        for (int i = 1; i < n; i++) {
 
            // Checking for lower buy value
            if (buy > prices[i])
                buy = prices[i];
 
            // Checking for higher profit
            else if (prices[i] - buy > max_profit)
                max_profit = prices[i] - buy;
        }
        return max_profit;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int prices[] = { 7, 1, 5, 6, 4 };
        int n = prices.length;
        int max_profit = maxProfit(prices, n);
        System.out.println(max_profit);
    }
}
 

Python

# Python program for the above approach:
 
 
def maxProfit(prices, n):
    buy = prices[0]
    max_profit = 0
    for i in range(1, n):
 
        # Checking for lower buy value
        if (buy > prices[i]):
            buy = prices[i]
 
        # Checking for higher profit
        elif (prices[i] - buy > max_profit):
            max_profit = prices[i] - buy
    return max_profit
 
 
# Driver code
if __name__ == '__main__':
 
    prices = [7, 1, 5, 6, 4]
    n = len(prices)
    max_profit = maxProfit(prices, n)
    print(max_profit)

C#

// C# code for the above approach
using System;
public class GFG {
 
    static int maxProfit(int[] prices, int n)
    {
        int buy = prices[0], max_profit = 0;
        for (int i = 1; i < n; i++) {
 
            // Checking for lower buy value
            if (buy > prices[i])
                buy = prices[i];
 
            // Checking for higher profit
            else if (prices[i] - buy > max_profit)
                max_profit = prices[i] - buy;
        }
        return max_profit;
    }
 
    static public void Main()
    {
 
        // Code
        int[] prices = { 7, 1, 5, 6, 4 };
        int n = prices.Length;
        int max_profit = maxProfit(prices, n);
        Console.WriteLine(max_profit);
    }
}
 

Javascript

function maxProfit( prices, n)
{
    let buy = prices[0], max_profit = 0;
    for (let i = 1; i < n; i++) {
 
        // Checking for lower buy value
        if (buy > prices[i])
            buy = prices[i];
 
        // Checking for higher profit
        else if (prices[i] - buy > max_profit)
            max_profit = prices[i] - buy;
    }
    return max_profit;
}
 
// Driver Code
 
    let prices= [ 7, 1, 5, 6, 4 ];
    let n =5;
    let max_profit = maxProfit(prices, n);
    console.log(max_profit);
     

输出

5

时间复杂度:O(N)。其中 N 是价格数组的大小。
辅助空间:O(1)