LeetCode OJ——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.


代码:

class Solution {
public:
    int maxProfit(vector<int>& prices) {

        if (prices.empty() || prices.size() == 1)
        {
            return 0;
        }
        else{
            int max = -pow(2,16);
            unsigned int pos = prices.size()-1;
            for (unsigned int i = 1; i<prices.size(); i++)
            {
                if ((prices[i] - prices[0]) > max)
                {
                    max = prices[i] - prices[0];
                    pos = i;
                }
            }
            for (unsigned int i = 1; i<prices.size()-1; i++)
            {
                if (pos >= i) //若卖出的最高价格的坐标大于此时买进的坐标,只需相减即可得此时买进的最大利润
                {
                    if (max <0 && pos == i) //表明后面所有的价格都比i-1的价格要低
                    {
                        pos = pos + 1;
                        max = prices[pos] - prices[i];
                    }
                    else{   //表明从i到末尾的价格至少有一个比i-1的要高
                        if (max < (prices[pos] - prices[i]))    //此时卖出所获利润最高
                        {
                            max = (prices[pos] - prices[i]);

                        }
                    }
                    continue;   //当前买进就不需再进行后续的遍历找最大利润了 
                }
                for (unsigned int j = prices.size() - 1; j>i; j--)
                {

                    if (prices[j] > prices[i])  //卖出价格比买进价格高
                    {
                        if (max < (prices[j] - prices[i]))
                        {
                            max = prices[j] - prices[i];
                            pos = j;
                        }
                    }
                }//for_j
            }//for_i
            return max >0 ? max : 0;
        }

    }
};

结果:
Submission Result: Time Limit Exceeded


思路:

  • 先以第一个元素为买进价格,然后考虑接下来最为合理的卖出价格,即prices[pos]

  • 然后遍历后续的价格,作为可能的买进价格。当pos >=i时,即表明最高卖出的价格时间在买进时间i的后面。max < (prices[pos] - prices[i])) 表明此时买进收益会更好,此时只需修改收益max即可。max <0 && pos == i 当max< 0时,说明之后卖出的价格都比买进的低。且pos == i表明此时即为卖出的最高价,为了后续减少遍历次数,即实现判断pos >= i故pos =pos+1;

  • o(╯□╰)o,结果超时。。。决定过段时间回过头再看问题,看能不能有一种重新的思路。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值