[LeetCode] Best Time to Buy and Sell Stock
2015-09-28 20:25
323 查看
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
分析一:使用两个辅助数组min_prices和max_prices。min_prices的第i个元素表示到第i天前最小的价格。max_prices的第i个元素表示第i天后最大的价格。时间复杂度O(n),空间复杂度O(n)
分析二:我们完全可以不借助于这两个数组。时间复杂度O(n),空间复杂度O(1)
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
分析一:使用两个辅助数组min_prices和max_prices。min_prices的第i个元素表示到第i天前最小的价格。max_prices的第i个元素表示第i天后最大的价格。时间复杂度O(n),空间复杂度O(n)
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; int prices_size = prices.size(); vector<int> min_prices(prices_size, prices[0]); vector<int> max_prices(prices_size, prices[prices_size - 1]); for (int i = 1; i < prices_size; i++) { if (prices[i] < min_prices[i-1]) { min_prices[i] = prices[i]; } else { min_prices[i] = min_prices[i-1]; } } for (int i = prices_size - 2; i >= 0 ; i--) { if (prices[i] > max_prices[i+1]) { max_prices[i] = prices[i]; } else { max_prices[i] = max_prices[i+1]; } } int max_gap = 0; for (int i = 0; i < prices_size; i++) { int temp_gap = max_prices[i] - min_prices[i]; if (temp_gap > max_gap) max_gap = temp_gap; } return max_gap; } };
分析二:我们完全可以不借助于这两个数组。时间复杂度O(n),空间复杂度O(1)
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; int min_price = prices[0]; int max_profit = 0; for (int i = 1; i < prices.size(); i++) { if (prices[i] < min_price) { min_price = prices[i]; } max_profit = max(max_profit, prices[i] - min_price); } return max_profit; } };
相关文章推荐
- Java基础知识强化之IO流笔记06:面试题之如果在finally之前有return
- 部署jar包到服务器
- poj 3126 Prime Path bfs
- CYC-NSFileManager的简单使用
- 建造者模式
- codeforces round 321 div2 题解
- opencv提取视频帧,将多张图片组合成视频(C++)
- 杭电
- [Machine Learning] Random Forest 随机森林
- druid 配置_StatFilter
- 《数学之美》之条件随机场与文法分析
- css margin 参数
- HDU 5478 Can you find it
- html code
- 简单对象写入文件
- ios-手势总结-清扫手势
- MYSQL数据操作表
- C. Beautiful Numbers
- C++拷贝构造函数
- Servlet中Service方法