leetcode刷题之旅——121. Best Time to Buy and Sell Stock
来源:互联网 发布:淘宝客自动转换工具 编辑:程序博客网 时间:2024/06/06 13:15
一道动态规划当中的简单题目,先拿简单题目加深自己对动态规划的理解。
题目大意:
给定我们一个数组,里面的第i个数字代表第i天的袜子价格,我们所需要做的就是以低价买入,高价卖出。最后我们返回我们可以获得利润的最大值。
例子:
example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
算法:
刚开始阅读这道题目,可能会想到一种算法就是从数组当中找到最小值,然后再找到最大值,相减就是最大利润。但是,这种算法会出错,因为最高价可能会出现在最低价前面。我们利用动态规划的方法来做这道题,首先我们当然要遍历整个数组,对于每个数我们判断其是否比当前最小值要小,然后更新最小值。这样做是为了在后面出现高价的时候,保证我们的利润最大。然后,如果当前值大于最小值,我们就用其减去最小值看看是否利润大于我们当前的利润。然后对于我们的利润进行更新,这样做保证了我们的利润是最大值。这样做的时间复杂度为O(n)。
代码:
class Solution{public: int maxProfit(vector<int>& prices) { int len=prices.size(); if(len==0) return 0; int minn=prices[0],maxx=0; for(int i=0;i<len;i++) { if(prices[i]<minn) minn=prices[i]; if(prices[i]-minn>maxx) maxx=prices[i]-minn; } return maxx; }};
0 0
- leetcode刷题之旅——121. Best Time to Buy and Sell Stock
- Leetcode —— Best Time to Buy and Sell Stock
- LeetCode——Best Time to Buy and Sell Stock
- LeetCode——Best Time to Buy and Sell Stock
- 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——Best Time to Buy and Sell Stock
- LeetCode—Best Time to Buy and Sell Stock
- Algorithms—121.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 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
- LeetCode之Best Time to Buy and Sell Stock II
- leetcode之Best Time to Buy and Sell Stock
- 水平/垂直滚动联动
- 123. Best Time to Buy and Sell Stock III
- 为什么eclipse不识别HttpServlet
- gevent+request+novel项目笔记
- Java代码实现多线程下载和断点续传
- leetcode刷题之旅——121. Best Time to Buy and Sell Stock
- SQL一些常见的查询练习
- 自动化运维工具ansible的使用详细教程
- Spring Mvc开发遇到的问题汇总
- 图解正向代理、反向代理、透明代理
- js leetcode
- POJ 1847 Tram(最短路)
- java中关于try、catch、finally中的细节分析
- Quick中的UIButton