Leetcode: Best Time to Buy and Sell Stock I II III

本文详细探讨了股票买卖中寻找最佳交易时机的问题,包括只允许进行一次交易、允许进行多次交易及最多允许两次交易的不同情况,并提供了多种高效的算法实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Best Time to Buy and Sell Stock I

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.

 1 int maxProfit(vector<int> &prices) {
 2     // Start typing your C/C++ solution below
 3     // DO NOT write int main() function
 4     if (prices.size() == 0)
 5         return 0;
 6 
 7     int low = prices[0];
 8     int profit = 0;
 9 
10     for (int i = 1; i < prices.size(); ++i)
11     {
12         low = min(prices[i], low);
13         profit = max(profit, prices[i] - low);
14     }
15 
16     return profit;
17 }
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if(prices.size() < 2)
            return 0;
        int cl = INT_MAX, maxp = 0;
        for(vector<int>::iterator i = prices.begin(); i != prices.end(); ++i) {
            cl = min(cl, *i);
            maxp = max(maxp, *i-cl);
        }
        return maxp;

    }
};

Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int p = 0;
 7         for (int i = 1; i < prices.size(); i++)
 8         {
 9             int delta = prices[i] - prices[i-1];
10             if (delta > 0)
11                 p += delta;
12             
13         }
14         return p;
15     }
16 };
 1 class Solution {
 2 
 3 public: 
 4 int maxProfit(vector<int> prices) 
 5 {
 6     if( prices.size() < 2)
 7         return 0;
 8 
 9     int maxProfit = 0;
10 
11     for(int i = 1; i < prices.size(); i++){
12         if(prices[i] > prices[i - 1])
13             maxProfit += prices[i] - prices[i - 1];
14     }
15     return maxProfit;
16 
17     }
18 };

Best Time to Buy and Sell Stock III

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

First consider the case that when we are only allowed to make one transaction. we can handle this easily with DP. If we move forward, any new price we meet will only affect our history result by two ways:

  1. will it be so low that it beats our previous lowest price?
  2. will it be so high that we should instead sell on this time to gain a higher profit (than the history record)? Similarly, we can move backward with the highest price and profit in record. Either way would take O(n) time.

Now consider the two transaction case. Since there will be no overlaps, we are actually dividing the whole time into two intervals.

We want to maximize the profit in each of them so the same method above will apply here. We are actually trying to break the day at each time instance, by adding the potential max profit before and after it together. By recording history and future for each time point, we can again do this within O(n) time.

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         // null check
 5         int len = prices.size();
 6         if (len==0) return 0;
 7 
 8         vector<int> historyProfit;
 9         vector<int> futureProfit;
10         historyProfit.assign(len,0);
11         futureProfit.assign(len,0);
12         int valley = prices[0];
13         int peak = prices[len-1];
14         int maxProfit = 0;
15 
16         // forward, calculate max profit until this time
17         for (int i = 0; i<len; ++i)
18         {
19             valley = min(valley,prices[i]);
20             if(i>0)
21             {
22                 historyProfit[i]=max(historyProfit[i-1],prices[i]-valley);
23             }
24         }
25 
26         // backward, calculate max profit from now, and the sum with history
27         for (int i = len-1; i>=0; --i)
28         {
29             peak = max(peak, prices[i]);
30             if (i<len-1)
31             {
32                 futureProfit[i]=max(futureProfit[i+1],peak-prices[i]);
33             }
34             maxProfit = max(maxProfit,historyProfit[i]+futureProfit[i]);
35         }
36         return maxProfit;
37     }
38 };

A new problem of completing at most m transactions can be efficiently solved by using the method below.

The profit of one transaction is price[i]-price[j] where i > j. We then can rewrite the expression to be: price[i]-price[i-1] + price[i-1]-price[i-2] + ... + price[j+1]-price[j]. If we construct an array of {diff[i]} = {price[i+1]-price[i]}, then the problem can be reduced to the maximum m segments sum problem on diff[], where m = 2 in this case. Then we can play the fancy dynamic programming to solve it.

Here is one solution of the maximum m segments sum problem. The running time is O(NM).


Let f[i][j] to be the maximum sum of j segments from the first i numbers, where the last element we choose is a[i]. We have two strategies to achieve it:

  1. Choosing the optimal j-1 segments from the first k numbers, and starting a new segment witha[i]:

f[i][j] = f[k][j-1] + a[i], where j-1 <= k <= i-1.

However, f[k][j-1] is the subproblems that we've already solved. If we memorize the optimal j-1segments, namely g[j-1] = max(f[k][j-1]), the state transition can be achieved in O(1):

f[i][j] = g[j-1] + a[i]

  1. Appending a[i] to the last segment in the first i-1 numbers

f[i][j] = f[i-1][j] + a[i].

Here is why we must choose a[i] in our strategies. If f[i-1][j] is not ends at a[i-1], then appending a[i] to f[i-1][j] will get j+1 segments, which violates the definition of f[i][j].

 1 class Solution {
 2     public:
 3         int maxProfit(vector<int> &prices) {
 4             int f[3] = {0};
 5             int g[3] = {0};
 6 
 7             int n = prices.size() - 1;
 8             for (int i = 0; i < n; ++i) {
 9                 int diff = prices[i+1] - prices[i];
10                 int m = min(i+1, 2);
11                 for (int j = m; j >= 1; --j) {
12                     f[j] = max(f[j], g[j-1]) + diff;
13                     g[j] = max(g[j], f[j]);
14                 }
15             }
16             return max(g[1], g[2]);
17         }
18     };

 

转载于:https://www.cnblogs.com/caijinlong/archive/2013/05/01/3053165.html

内容概要:论文提出了一种基于空间调制的能量高效分子通信方案(SM-MC),将传输符号分为空间符号和浓度符号。空间符号通过激活单个发射纳米机器人的索引来传输信息,浓度符号则采用传统的浓度移位键控(CSK)调制。相比现有的MIMO分子通信方案,SM-MC避免了链路间干扰,降低了检测复杂度并提高了性能。论文分析了SM-MC及其特例SSK-MC的符号错误率(SER),并通过仿真验证了其性能优于传统的MIMO-MC和SISO-MC方案。此外,论文还探讨了分子通信领域的挑战、优势及相关研究工作,强调了空间维度作为新的信息自由度的重要性,并提出了未来的研究方向和技术挑战。 适合人群:具备一定通信理论基础,特别是对纳米通信和分子通信感兴趣的科研人员、研究生和工程师。 使用场景及目标:①理解分子通信中空间调制的工作原理及其优势;②掌握SM-MC系统的具体实现细节,包括发射、接收、检测算法及性能分析;③对比不同分子通信方案(如MIMO-MC、SISO-MC、SSK-MC)的性能差异;④探索分子通信在纳米网络中的应用前景。 其他说明:论文不仅提供了详细的理论分析和仿真验证,还给出了具体的代码实现,帮助读者更好地理解和复现实验结果。此外,论文还讨论了分子通信领域的标准化进展,以及未来可能的研究方向,如混合调制方案、自适应调制技术和纳米机器协作协议等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值