刷题121. Best Time to Buy and Sell Stock
Posted siweihz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了刷题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.
以上是关于刷题121. Best Time to Buy and Sell Stock的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode OJ 121. Best Time to Buy and Sell Stock
Leetcode 121 Best Time to Buy and Sell Stock
算法分析与设计第一周121.Best Time to Buy and Sell Stock&122. Best Time to Buy and Sell Stock II
121. Best Time to Buy and Sell Stock