leetcode-Best Time to Buy and Sell Stock(2014.2.16)
来源:互联网 发布:linux vim怎么保存 编辑:程序博客网 时间:2024/06/06 13:01
用两层遍历的方法超时:
class Solution {
public:
int maxProfit(vector<int> &prices) {
int maxPro=0;
for(int i=0;i<prices.size();i++){
for(int j=i+1;j<prices.size();j++){
int m=prices[j]-prices[i];
if(m>maxPro) maxPro=m;
}
}
return maxPro;
}
};
改用记录最低值得方法,一次遍历则完成,免去大量重复计算,注意判断长度以确保程序的健壮性:
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size()<2) return 0;
int maxPro=0;
int low=prices[0];
for(int i=0;i<prices.size();i++){
int m=prices[i]-low;
if(prices[i]<low) low=prices[i];
if(m>maxPro) maxPro=m;
}
return maxPro;
}
};
0 0
- leetcode-Best Time to Buy and Sell Stock(2014.2.16)
- leetcode-Best Time to Buy and Sell Stock(2014.2.17)
- leetcode 16: Best Time to Buy and Sell Stock III
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- 数据结构基础知识
- leetcode-Best Time to Buy and Sell Stock II(2014.2.17)
- centOS命令随笔(3)-- permissions
- 比较详细Python正则表达式操作指南(re使用)[4]
- RSA加密算法
- leetcode-Best Time to Buy and Sell Stock(2014.2.16)
- 蓝桥杯 PREV-27 蚂蚁感冒 模拟
- 比较详细Python正则表达式操作指南(re使用)[5]
- mac中安装maven3.2.1
- leetcode-Best Time to Buy and Sell Stock(2014.2.17)
- 比较详细Python正则表达式操作指南(re使用)[6]
- 【APIO2010】特别行动队
- 为程序员开一剂提高职业素养的良方
- leetcode-Balanced Binary Tree(2014.1.27)