LeetCode -- 121. Best Time to Buy and Sell Stock
来源:互联网 发布:java mvc web项目实例 编辑:程序博客网 时间:2024/05/18 16:39
题目:
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.
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.
思路:
滴滴牛客网视频面试的时候正好让写这道题,可惜我当时没刷LeetCode,先写了个暴力,然后又写了一个dp的,还好最后面试官还算满意~
设
C++代码如下:
class Solution {public: int maxProfit(vector<int>& prices) { int max = 0, index = 0, len = prices.size(); if(len == 0) return 0; vector<int> d(len,0); d[0] = 0; for(int i=1;i<len;i++) { if(prices[i]<prices[i-1] && prices[i] < prices[index]) { index = i; d[i] = 0; } else { d[i] = prices[i] - prices[index]; } } for(int i=0;i<len;i++) { if(d[i]>max) max = d[i]; } return max; }};
阅读全文
0 0
- 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
- [leetcode] 121. Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock LeetCode
- [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
- 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
- LeetCode 121. Best Time to Buy and Sell Stock
- 121.[Leetcode]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
- 数据结构上机作业3:栈——八皇后
- 深度优先搜索例1--走迷宫问题
- Web.xml详解
- STC15系列单片机命名规则
- yii2.0 验证码功能的实现
- LeetCode -- 121. Best Time to Buy and Sell Stock
- Notification详解(三)
- PI复制新CC
- Cloudstack-agent KVM计算节点的安装
- Spring MVC工作流程
- liunx命令(3)
- (七)android recovery代码修改之原生建议
- 二部图(广搜染色)
- LeetCode 44 Wildcard Matching