LeetCode——Best Time to Buy and Sell Stock
来源:互联网 发布:无人驾驶数据标注 编辑:程序博客网 时间:2024/06/05 15:19
LeetCode——Best Time to Buy and Sell Stock
# 121
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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.
这一题的目的是求数组中,找出两个相差最大的元素,必须是后一个元素减去前一个元素。这一题明显是动态规划。当然可以用暴力破解,时间复杂度为
有一种简单的思想就是,就是使用一次遍历,记录遍历过程中的最小元素,并将当前值与当前遍历的最小元素的差记录为最大利润。遍历结束后,即能得到最大利润。
- C++
class Solution {public: int maxProfit(vector<int>& prices) { int res = 0, buy = INT_MAX; for (int price : prices) { buy = min(buy, price); res = max(res, price - buy); } return res; }};
动态规划的方法,其实思想是和前面做过的一题Maximum Subarray 很相似。就是要用两个变量分别维护局部最优和全局最优。
- C++
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size() == 0) return 0; int local = 0; int global = 0; for(int i = 0;i < prices.size() - 1;i++) { local = max(local + prices[i + 1] - prices[i],0); global = max(local,global); } return global; }};
这里的动态规划思想和Maximum Subarray的思想是一样的,设置两个变量,维护局部最优和全局最优。
- Python
class Solution: def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 1: return 0 low = prices[0] maxprofit = 0 for i in range(len(prices)): if prices[i] < low: low = prices[i] maxprofit = max(maxprofit, prices[i] - low) return maxprofit
阅读全文
0 0
- 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
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- DP——Best Time to Buy and Sell Stock
- Algorithms—121.Best Time to Buy and Sell Stock
- LeetCode121—Best Time to Buy and Sell Stock
- LeetCode122—Best Time to Buy and Sell Stock II
- LeetCode123—Best Time to Buy and Sell Stock III
- LeetCode188—Best Time to Buy and Sell Stock IV
- Leetcde——121 Best Time to Buy and Sell Stock && 123 Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- leetcode——309——Best Time to Buy and Sell Stock with Cooldown
- C语言的关键字
- 平衡二叉树,AVL树之图解篇
- leetcode解题方案--032--Longest Valid Parentheses
- 使用construct 2做进阶游戏
- C语言操作符小结
- LeetCode——Best Time to Buy and Sell Stock
- Netty 常量池实现以及ChannelOption与Attribute作用分析
- HDOJ2088 Box of Bricks
- java(Web)中相对路径,绝对路径问题总结
- 二叉树镜像
- iptables配置详解
- 计算机专业及软件开发推荐书籍
- 使用Filter过滤器解决字符编码问题
- malloclab 实验详解(动态分配器如何设计)