买卖股票的最佳时机

买卖股票的最佳时机

给定一个数组prices,其中prices[i] 是一支给定股票第i天的价格

设计一个算法来计算你所能获取的最大利润

1. 只能买卖一次
思路:从1开始到最后,记录当前位置前面的最小值,获取当下卖出的盈利,最终比较得到最大盈利

int getMaxProfit(int prices[],int len)
{
    if(len <= 1)
    {
        return 0;
    }
    int buyInMin = prices[0];
    int sellMax = 0;
    for(int i = 1;i < len;i++)
    {
        if(prices[i] - buyInMin > sellMax)
        {
            sellMax = prices[i] - buyInMin;
        }
        if(prices[i] < buyInMin)
        {
            buyInMin = prices[i];
        }
    }
    sellMax = sellMax > 0 ? sellMax:0;
    qDebug() << "\nmax profit: " << sellMax << endl;
    return sellMax;
}

2. 可买卖多次,多次买卖一只股票,但不能同时参与多笔交易
解法一:

/*
 * 买卖股票的最佳时机 :可买卖多次(多次买卖一只股票,但不能同时参与多笔交易),求最大盈利
 *思路: 贪心算法1
 *     今天持有股票:如果明天不涨,继续持有不卖;如果明天跌,今天卖出,不持有
 *     今天不持有股票:如果明天涨,今天买入;如果明天跌,继续持有
 */
int getMaxProfit1(int prices[],int len)
{
    if(len <= 1)
    {
        return 0;
    }
    int totalProfit = 0; //总盈利
    int curStatus = 0; // 0 不持有股票,1  持有股票
    for(int i = 0;i < len - 1;i++)
    {
        if(curStatus == 0 && prices[i] < prices[i+1]) //最后一天不能买入
        {
            curStatus = 1; //买入
            totalProfit -= prices[i];
        }
        else if(curStatus == 1 && prices[i] > prices[i+1]) //第一天不能卖出
        {
            curStatus = 0; //卖出
            totalProfit += prices[i];
        }
    }
    if(curStatus == 1)
    {
        curStatus = 0; //卖出
        totalProfit += prices[len - 1];
    }
    qDebug() << "\nmax profit: " << totalProfit << endl;
    return totalProfit;
}

解法二:

/*
 * 买卖股票的最佳时机 :可买卖多次(多次买卖一只股票,但不能同时参与多笔交易),求最大盈利
 *思路: 贪心算法2
 *     两两上升盈利的总和
 *
 */
int getMaxProfit2(int prices[],int len)
{
    if(len <= 1)
    {
        return 0;
    }
    int totalProfit = 0;
    for(int i = 0; i< len - 1;i++)
    {
        if(prices[i+1] > prices[i])
        {
            int v = prices[i+1] - prices[i];
            totalProfit += v;
        }
    }
    qDebug() << "\nmax profit: " << totalProfit << endl;
    return totalProfit;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值