LeetCode | Best Time to Buy and Sell Stock

题目:

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个价格的数组转化成n-1个隔日的盈亏数组,即表示前一日买后一日卖的收入。目标问题变成了求第二个数组连续和的最大值。

代码:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(prices.size() == 0 || prices.size() == 1)
        {
            return 0;
        }
        
        int* profit = new int[prices.size()-1];
        
        for(int i = 0; i < prices.size()-1; i++)
        {
            profit[i] = prices[i+1]-prices[i];
        }
        
        int max = profit[0];
        int cur = profit[0];
        
        for(int i = 1; i < prices.size()-1; i++)
        {
            if(cur < 0)
            {
                cur = profit[i];
            }
            else
            {
                cur += profit[i];
            }
            if(max < cur)
            {
                max = cur;
            }
        }
        return max<0?0:max;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11880335
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞