<LeetCode OJ> 121. /122. Best Time to Buy and Sell Stock(I / II)

本文提出两种股票交易算法,一种适用于仅能进行一次买卖的情况,通过动态规划寻找最大利润;另一种适用于可进行多次买卖的情况,采用贪心算法实现。两种算法均实现了高效的时间复杂度。

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

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.



分析:

思路首先:动态规划
遍历数组时记录当前价格以前的最小价格curMin,记录昨天能够获得的最大利润maxProfit
对于今天,为了能获得此刻的最大利润,显然只能卖,或者不做任何操作
如果不做任何操作,显然还是昨天maxProfit
如果卖掉今天天的股票,显然prices[i]-curMin

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size()<=1)
            return 0;
        int curMin=prices[0];
        int maxProfit=0;
        for(int i=1;i<prices.size();i++)
        {
            maxProfit=max(maxProfit,prices[i]-curMin);
            curMin=min(curMin,prices[i]);//获得历史最小价格的股票
        }
        return maxProfit;
    }
};




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).

同一时间不能做多次交易(买一次再卖一次,或者卖一次再买一次算一次交易),意思就是说在你买股票之前你必须卖掉股票

(即你手头最多允许保留一只股票,同时隐含了每次只能交易一次的意思)


分析:

题目理解错误,刚开始没有任何思路....这题通过率40%,我的内心是崩溃的!!!
题目:用一个数组表示股票每天的价格,数组的第i个数表示股票在第i天的价格。设计一个算法找出最大利润
但一次只能交易一支股票,也就是说手上最多只能持有一支股票,求最大收益。
分析:贪心法。从前向后遍历数组,只要当天的价格高于前一天的价格(即为了最大利润,只要有利润存在就利用交易次数的无限制贪心的获取),就累加到收益中。
代码:时间O(n),空间O(1)。

class Solution {  
public:  
    int maxProfit(vector<int>& prices) {  
        if(prices.size() < 2)   
            return 0;    
        int profit = 0;    
        for(auto ite = prices.begin()+1; ite != prices.end(); ite++)   
            profit += max(*ite - *(ite-1),0);    
        return profit;    
    }  
}; 



注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!

原文地址:http://blog.youkuaiyun.com/ebowtang/article/details/50524380

原作者博客:http://blog.youkuaiyun.com/ebowtang

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值