【LeetCode】Best Time to Buy and Sell Stock 程序员炒股 part.1
来源:互联网 发布:2015云计算市场规模 编辑:程序博客网 时间:2024/06/06 01:55
【题目一】
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.
有这样一个数组,保存了每天的股票价格,找到最佳买点和卖点,输出最大盈利。
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
【解析】
遍历数组找到最大值和最小值,输出两者只差。
值得注意的是,当最大值出现在最小值前,则会出错,因为我们这是股票买卖,手上有票才能卖。
因此,思路优化一下。
按顺序遍历一遍数组,每此都保存一个当前最小值,和当前最大盈利,用当前值与当前最小值做差,将其与当前最大盈利比较,较大者赋给当前最大盈利。
最后输出最大盈利。
此题简单,直接上程序:
class Solution {public: int maxProfit(vector<int>& prices) { int min_price = INT_MAX; int max_profit = 0; for(int i = 0 ; i < prices.size(); i++) { min_price = min(min_price, prices[i]); max_profit = max(prices[i] - min_price, max_profit); } return max_profit; }};【题目二】
Say you have an array for which the ith element is the price of a given stock on day i.Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
与题一类似,只是可以进行多次买卖(同一天不能即买又卖)。
【解析】
原先思路是按照第一题先遍历一遍,找到最大盈利之后,接着后面的数字进行下一次遍历。
正确的思路是只要当前数值比后面的数值小,就做差,将差值累和,最后输出。
原先的思路还是复杂了,虽然正确的思路有点不讲道理,但却是没能想到。
程序如下:
class Solution {public: int maxProfit(vector<int>& prices) { int sum_profit = 0; if(prices.size() == 0) return 0; for(int i = 0; i < prices.size()-1; i++) if(prices[i+1] > prices[i]) sum_profit += prices[i+1] - prices[i]; return sum_profit; }};
- 【LeetCode】Best Time to Buy and Sell Stock 程序员炒股 part.1
- 【LeetCode】Best Time to Buy and Sell Stock 程序员炒股 part.2
- 【LeetCode】Best Time to Buy and Sell Stock 程序员炒股 part.3
- 【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
- tomcat环境变量的配置
- 【机房个人重构】导出Excel
- 关于Mac版XAMPP 403 Access forbidden的解决
- android studio下百度地图sdk的初体验
- 2014山东省第五届ACM省赛 Factorial
- 【LeetCode】Best Time to Buy and Sell Stock 程序员炒股 part.1
- 深入分析Android native exception框架
- 27 vector
- git clone --recursive 参数在Jenkins里的配置实现
- homebrew常用命令
- 微信支付成功后推荐关注栏目规则:
- iOS网络编程之TCP/IP应用篇(二)-框架的二次封装
- android数据加密(二)AES加密
- android 根据时间是否过期进行文件的删除