首页 > 其他 > 详细

刷题121. Best Time to Buy and Sell Stock

时间:2020-03-10 20:05:47      阅读:43      评论:0      收藏:0      [点我收藏+]

一、题目说明

题目121. Best Time to Buy and Sell Stock,有一列数,第i个元素是第i天股票的价格,只允许一次交易(买和卖),计算如何利润最大化。难度是Easy!

二、我的解答

不动脑子,用brute force方法:

class Solution{
    public:
        int maxProfit(vector<int>& prices){
            int len = prices.size();
            if(len<=1) return 0;

            int max = 0;
            
            for(int i=0;i<len-1;i++){
                for(int j=i+1;j<len;j++){
                    if(prices[j]-prices[i]>max){
                        max = prices[j]-prices[i];
                    }
                }
            }
            return max; 
        }
};
Runtime: 788 ms, faster than 11.32% of C++ online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 9.6 MB, less than 77.98% of C++ online submissions for Best Time to Buy and Sell Stock.

三、优化措施

一遍扫描,计算最小值,计算最大利润:

class Solution{
    public:
        int maxProfit(vector<int>& prices){
            int len = prices.size();
            if(len<=1) return 0;
            int minPrice=INT_MAX,maxProfit=0;
            for(int i=0;i<len;i++){
                if(prices[i]<minPrice){
                    minPrice = prices[i];
                }else if(prices[i]-minPrice>maxProfit) {
                        maxProfit = prices[i]-minPrice;
                }
            }

            return maxProfit; 
        }
};

性能如下:

Runtime: 4 ms, faster than 98.50% of C++ online submissions for Best Time to Buy and Sell Stock.
Memory Usage: 9.5 MB, less than 86.24% of C++ online submissions for Best Time to Buy and Sell Stock.

刷题121. Best Time to Buy and Sell Stock

原文:https://www.cnblogs.com/siweihz/p/12267828.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!