(算法分析Week8)Best Time to Buy and Sell Stock[Easy]
来源:互联网 发布:苹果mac如何装虚拟机 编辑:程序博客网 时间:2024/06/14 19:44
121.Best Time to Buy and Sell Stock[Easy]
题目来源
Description
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.
给出一组数据,第i个数代表第i天石头的价格,选择在第i天买入在第j天(i < j)卖出,使得利润最大。
Solution
动态规划的问题。
两种思路:
(1)找到目前为止最小的那个数,然后找再它之后最大的那个数,求它们的差值即为最大利润值。
(2)考虑相邻两天石头的“差价”,目前的利润值+=price[i] - price[i-1],若利润值大于0,说明在第i天卖出比在i-1天更好;若小于0,说明第i天的石头价格比先前更低,当前利润值清零,继续往后比较,若能找到新的利润值比原来的最大利润值大,则替换数据。
*说的不是很清楚,对着代码举个例子就明白了
Complexity analysis
O(n)
Code
(1)找最大差值,限制往后找。class Solution {public: int maxProfit(vector<int>& prices) { int maxPro = 0; int minPrice = INT_MAX; for(int i = 0; i < prices.size(); i++){ minPrice = min(minPrice, prices[i]); maxPro = max(maxPro, prices[i] - minPrice); } return maxPro; }};(2)动态规划class Solution {public: int maxProfit(vector<int>& prices) { int maxPro = 0; int curPro = 0; for (int i = 1; i < prices.size(); i++) { curPro = max(0, curPro += prices[i] - prices[i-1]); maxPro = max(curPro, maxPro); } return maxPro; }};
Result
- (算法分析Week8)Best Time to Buy and Sell Stock[Easy]
- Best Time to Buy and Sell Stock(算法分析week9)
- 121. Best Time to Buy and Sell Stock [easy] (Python)
- Easy 121题 Best Time to Buy and Sell Stock
- [Easy]Best Time to Buy and Sell Stock
- 121. Best Time to Buy and Sell Stock -Easy
- Easy : 122. Best Time to Buy and Sell Stock II
- 【Leetcode-Easy-121】Best Time to Buy and Sell Stock
- 算法<Best Time to Buy and Sell Stock>
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 强类型 JavaScript 的解决方案
- elasticsearch异常Elasticsearch requires at least Java 8 but your Java XXXXX
- NOIP2015提高组——运输计划(transport)
- javaee的几个元注解
- 数据转换函数
- (算法分析Week8)Best Time to Buy and Sell Stock[Easy]
- C/C++ 中的0长数组(柔性数组)
- Python lambda 表达式
- java序列化和数据库设计
- Excel 时间差 小时小数 日期对应星期
- es6环境搭建(2)创建js编译任务。
- 【VINS算法分析之一】VINS-Mono(草稿)
- 今天又跟超级社区hsr003学了一招,如何备份虚拟币钱包及如何导入钱包
- Python.Numpy学习零碎笔记之随机数生成