leetcode121——Best Time to Buy and Sell Stock
2018-03-26 21:49
316 查看
题目大意:给出股票在i天的价格数组prices[i],一个人手里最多持有一只股票,也就是他再买入之前必须卖出,问这个人的最大收益是多少
分析:dp。简单的二重循环会超时,所以我们考虑遍历一次就能求解的方法,在遍历过程中用min记录股票的最小值,不断更新profit收益来记录卖出时的最大值。
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1) return 0;
int min = prices[0];
int profit = 0;
for (int i = 1;i < prices.size();i++) {
if (min > prices[i]) {
min = prices[i];
}
else {
if (profit < prices[i] - min) {
profit = prices[i] - min;
}
}
}
return profit;
}
};
分析:dp。简单的二重循环会超时,所以我们考虑遍历一次就能求解的方法,在遍历过程中用min记录股票的最小值,不断更新profit收益来记录卖出时的最大值。
代码:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1) return 0;
int min = prices[0];
int profit = 0;
for (int i = 1;i < prices.size();i++) {
if (min > prices[i]) {
min = prices[i];
}
else {
if (profit < prices[i] - min) {
profit = prices[i] - min;
}
}
}
return profit;
}
};
相关文章推荐
- Leetcode 121. Best Time to Buy and Sell Stock 最佳股票售卖时(动态规划,数组,模拟)
- leetcode_121题——Best Time to Buy and Sell Stock(动态规划)
- Leetcode 121 Best Time to Buy and Sell Stock
- LeetCode 121, 122, 123. Best Time to Buy and Sell Stock i, ii, iii
- leetcode121- Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock
- leetcode(121). Best Time to Buy and Sell Stock
- leetcode 121 Best Time to Buy and Sell Stock
- 【leetcode】121. Best Time to Buy and Sell Stock【java】
- Leetcode:121. Best Time to Buy and Sell Stock
- LeetCode-121-Best Time to Buy and Sell Stock-E
- [LeetCode] 121. Best Time to Buy and Sell Stock ❤
- leetcode-java-121. Best Time to Buy and Sell Stock
- LeetCode 121 Best Time to Buy and Sell Stock题解
- leetcode-Best Time to Buy and Sell Stock-121
- LeetCode:121. Best Time to Buy and Sell Stock
- 【LeetCode-面试算法经典-Java实现】【121-Best Time to Buy and Sell Stock(最佳买卖股票的时间)】
- leetcode_121 Best Time to Buy and Sell Stock
- leetcode 121 122 123 . Best Time to Buy and Sell Stock
- [Leetcode] 121. Best Time to Buy and Sell Stock 解题报告