📌  相关文章
📜  股票买入卖出以最大化利润的 C++ 程序

📅  最后修改于: 2022-05-13 01:57:49.808000             🧑  作者: Mango

股票买入卖出以最大化利润的 C++ 程序

股票每天的成本以数组的形式给出,找出你在那些日子里通过买卖可以获得的最大利润。例如,如果给定数组是 {100, 180, 260, 310, 40, 535, 695},则可以通过在第 0 天买入,在第 3 天卖出来获得最大利润。再次在第 4 天买入并在第 6 天卖出. 如果给定的价格数组按降序排序,则根本无法赚取利润。

幼稚的方法:一种简单的方法是尝试在获利的每一天买入股票并卖出,并不断更新迄今为止的最大利润。

下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
  
// Function to return the maximum profit
// that can be made after buying and
// selling the given stocks
int maxProfit(int price[], 
              int start, int end)
{
    // If the stocks can't be bought
    if (end <= start)
        return 0;
  
    // Initialise the profit
    int profit = 0;
  
    // The day at which the stock
    // must be bought
    for (int i = start; i < end; i++) 
    {
        // The day at which the
        // stock must be sold
        for (int j = i + 1; j <= end; j++) 
        {
            // If buying the stock at ith day and
            // selling it at jth day is profitable
            if (price[j] > price[i]) 
            {
                // Update the current profit
                int curr_profit = price[j] - price[i] + 
                                  maxProfit(price, 
                                            start, i - 1) + 
                                  maxProfit(price, 
                                            j + 1, end);
  
                // Update the maximum profit so far
                profit = max(profit, curr_profit);
            }
        }
    }
    return profit;
}
  
// Driver code
int main()
{
    int price[] = {100, 180, 260, 310,
                    40, 535, 695};
    int n = sizeof(price) / sizeof(price[0]);
    cout << maxProfit(price, 0, n - 1);
    return 0;
}


C++
// C++ Program to find best buying 
// and selling days
#include 
using namespace std;
  
// This function finds the buy sell
// schedule for maximum profit
void stockBuySell(int price[], int n)
{
    // Prices must be given for at 
    // least two days
    if (n == 1)
        return;
  
    // Traverse through given price array
    int i = 0;
    while (i < n - 1) 
    {
        // Find Local Minima
        // Note that the limit is (n-2) as we are
        // comparing present element to the next element
        while ((i < n - 1) && 
               (price[i + 1] <= price[i]))
            i++;
  
        // If we reached the end, break
        // as no further solution possible
        if (i == n - 1)
            break;
  
        // Store the index of minima
        int buy = i++;
  
        // Find Local Maxima
        // Note that the limit is (n-1) as we are
        // comparing to previous element
        while ((i < n) && 
               (price[i] >= price[i - 1]))
            i++;
  
        // Store the index of maxima
        int sell = i - 1;
  
        cout << "Buy on day: " << buy
             << "     Sell on day: " << 
                sell << endl;
    }
}
  
// Driver code
int main()
{
    // Stock prices on consecutive days
    int price[] = {100, 180, 260, 
                   310, 40, 535, 695};
    int n = sizeof(price) / sizeof(price[0]);
  
    // Function call
    stockBuySell(price, n);
  
    return 0;
}
  
// This is code is contributed by rathbhupendra


C++
// C++ program to implement
// the above approach
#include 
using namespace std;
  
// Preprocessing helps the code 
// run faster
#define fl(i, a, b) 
for (int i = a; i < b; i++)
  
// Function that return
int maxProfit(int* prices, int size)
{
    // maxProfit adds up the difference 
    // between adjacent elements if they 
    // are in increasing order
    int maxProfit = 0;
  
    // The loop starts from 1 as its 
    // comparing with the previous
    fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit
        += prices[i] - prices[i - 1];
    return maxProfit;
}
  
// Driver code
int main()
{
    int prices[] = {100, 180, 260, 
                    310, 40, 535, 695};
    int N = sizeof(prices) / sizeof(prices[0]);
    cout << maxProfit(prices, N) << endl;
    return 0;
}
// This code is contributed by Kingshuk Deb


输出:

865

有效的方法:如果我们只允许买卖一次,那么我们可以使用以下算法。两个元素之间的最大差异。在这里,我们可以多次买卖。
下面是这个问题的算法。

  1. 找到局部最小值并将其存储为起始索引。如果不存在,则返回。
  2. 找到局部最大值。并将其存储为结束索引。如果我们到达结尾,则将结尾设置为结束索引。
  3. 更新解决方案(增加买卖对的计数)
  4. 如果没有到达终点,重复上述步骤。

C++

// C++ Program to find best buying 
// and selling days
#include 
using namespace std;
  
// This function finds the buy sell
// schedule for maximum profit
void stockBuySell(int price[], int n)
{
    // Prices must be given for at 
    // least two days
    if (n == 1)
        return;
  
    // Traverse through given price array
    int i = 0;
    while (i < n - 1) 
    {
        // Find Local Minima
        // Note that the limit is (n-2) as we are
        // comparing present element to the next element
        while ((i < n - 1) && 
               (price[i + 1] <= price[i]))
            i++;
  
        // If we reached the end, break
        // as no further solution possible
        if (i == n - 1)
            break;
  
        // Store the index of minima
        int buy = i++;
  
        // Find Local Maxima
        // Note that the limit is (n-1) as we are
        // comparing to previous element
        while ((i < n) && 
               (price[i] >= price[i - 1]))
            i++;
  
        // Store the index of maxima
        int sell = i - 1;
  
        cout << "Buy on day: " << buy
             << "     Sell on day: " << 
                sell << endl;
    }
}
  
// Driver code
int main()
{
    // Stock prices on consecutive days
    int price[] = {100, 180, 260, 
                   310, 40, 535, 695};
    int n = sizeof(price) / sizeof(price[0]);
  
    // Function call
    stockBuySell(price, n);
  
    return 0;
}
  
// This is code is contributed by rathbhupendra

输出:

Buy on day: 0     Sell on day: 3
Buy on day: 4     Sell on day: 6

时间复杂度:外循环一直运行到我变成 n-1。内部两个循环在每次迭代中增加 I 的值。所以整体时间复杂度是 O(n)

谷峰方法:

在这种方法中,我们只需要找到下一个更大的元素并将其从当前元素中减去,这样差异就会不断增加,直到达到最小值。如果序列是递减序列,则可能的最大利润为 0。

C++

// C++ program to implement
// the above approach
#include 
using namespace std;
  
// Preprocessing helps the code 
// run faster
#define fl(i, a, b) 
for (int i = a; i < b; i++)
  
// Function that return
int maxProfit(int* prices, int size)
{
    // maxProfit adds up the difference 
    // between adjacent elements if they 
    // are in increasing order
    int maxProfit = 0;
  
    // The loop starts from 1 as its 
    // comparing with the previous
    fl(i, 1, size) if (prices[i] > prices[i - 1]) maxProfit
        += prices[i] - prices[i - 1];
    return maxProfit;
}
  
// Driver code
int main()
{
    int prices[] = {100, 180, 260, 
                    310, 40, 535, 695};
    int N = sizeof(prices) / sizeof(prices[0]);
    cout << maxProfit(prices, N) << endl;
    return 0;
}
// This code is contributed by Kingshuk Deb

输出:

865

时间复杂度:O(n)
辅助空间: O(1)

请参阅完整的股票买卖以最大化利润的文章了解更多详情!