码迷,mamicode.com
首页 > 其他好文 > 详细

刷题121. Best Time to Buy and Sell Stock

时间:2020-03-10 20:19:22      阅读:42      评论:0      收藏:0      [点我收藏+]

标签:++   code   股票   vector   最小   time   lin   price   如何   

一、题目说明

题目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

标签:++   code   股票   vector   最小   time   lin   price   如何   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!