zoukankan      html  css  js  c++  java
  • 刷题121. Best Time to Buy and Sell Stock

    一、题目说明

    题目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.
    
    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    [bzoj1113][Poi2008]海报PLA
    [CF1111D]Destroy the Colony
    [CF1111E]Tree
    [CF1111C]Creative Snap
    [洛谷P5136]sequence
    [洛谷P5190][COCI 2010] PROGRAM
    [洛谷P5137]polynomial
    US Open 2016 Contest
    【hackerrank】Week of Code 26
    usaco中遇到的问题
  • 原文地址:https://www.cnblogs.com/siweihz/p/12267828.html
Copyright © 2011-2022 走看看