刷题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.
posted @ 2020-03-10 19:24  siwei718  阅读(116)  评论(0编辑  收藏  举报