121. Best Time to Buy and Sell Stock【easy】
121. Best Time to Buy and Sell Stock【easy】
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.
解法一:
先看@keshavk 的解析和代码
We take prices array as [5, 6, 2, 4, 8, 9, 5, 1, 5]
In the given problem, we assume the first element as the stock with lowest price.
Now we will traverse the array from left to right. So in the given array 5 is the stock we bought. So next element is 6. If we sell the stock at that price we will earn profit of $1.
Prices: [5, 6, 2, 4, 8, 9, 5, 1, 5]
Profit: Bought:5 Sell:6 Profit:$1 max profit=$1
Now the next element is 2 which have lower price than the stock we bought previously which was 5. So if we buy this stock at price $2 and sells it in future then we will surely earn more profit than the stock we bought at price 5. So we bought stock at $2.
Profit: Bought:2 Sell:- Profit:- max profit=$1
Next element is 4 which has higher price than the stock we bought. So if we sell the stock at this price.
Profit: Bought:2 Sell:4 Profit:$2 max profit=$2
Moving further, now the next stockprice is $8. We still have $2 stock we bought previously. If instead of selling it at price $4, if we sell it for $8 then the profit would be $6.
Profit: Bought:2 Sell:8 Profit:$6 max profit=$6
Now next stock is of $9 which is also higher than the price we bought at ($2).
Profit: Bought:2 Sell:9 Profit:$7 max profit=$7
Now the next stock is $5. If we sell at this price then we will earn profit of $3, but we already have a max profit of $7 because of our previous transaction.
Profit: Bought:2 Sell:5 Profit:$3 max profit=$7
Now next stock price is $1 which is less than the stock we bought of $2. And if we buy this stock and sell it in future then obviously we will gain more profit. So the value of bought will become $1.
Profit: Bought:1 Sell:- Profit:- max profit=$7
Now next stock is of $5. So this price is higher than the stock we bought.
Profit: Bought:1 Sell:5 Profit:$4 max profit=$7
But our maximum profit will be $7.
public int maxProfit(int[] prices) {
int ans=;
if(prices.length==)
{
return ans;
}
int bought=prices[];
for(int i=;i<prices.length;i++)
{
if(prices[i]>bought)
{
if(ans<(prices[i]-bought))
{
ans=prices[i]-bought;
}
}
else
{
bought=prices[i];
}
}
return ans;
}
解法二:
结合上面解法一的思路,重新简化代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min_value = INT_MAX;
int max_value = ;
for (int i = ; i < prices.size(); ++i) {
min_value = min(min_value, prices[i]);
max_value = max(max_value, prices[i] - min_value);
}
return max_value;
}
};
写的过程中参考了@linjian2015 的代码
解法三:
public int maxProfit(int[] prices) {
int maxCur = 0, maxSoFar = 0;
for(int i = 1; i < prices.length; i++) {
maxCur = Math.max(0, maxCur += prices[i] - prices[i-1]);
maxSoFar = Math.max(maxCur, maxSoFar);
}
return maxSoFar;
}
参考@jaqenhgar 的代码
The logic to solve this problem is same as "max subarray problem" using Kadane's Algorithm. Since no body has mentioned this so far, I thought it's a good thing for everybody to know.
All the straight forward solution should work, but if the interviewer twists the question slightly by giving the difference array of prices, Ex: for {1, 7, 4, 11}, if he gives {0, 6, -3, 7}, you might end up being confused.
Here, the logic is to calculate the difference (maxCur += prices[i] - prices[i-1]) of the original array, and find a contiguous subarray giving maximum profit. If the difference falls below 0, reset it to zero.
*maxCur = current maximum value
*maxSoFar = maximum value found so far
关于 Kadane's Algorithm 说明如下:
Visualization of how sub-arrays change based on start and end positions of a sample. Each possible contiguous sub-array is represented by a point on a colored line. That point's y-coordinate represents the sum of the sample. Its x-coordinate represents the end of the sample, and the leftmost point on that colored line represents the start of the sample. In this case, the array from which samples are taken is [2, 3, -1, -20, 5, 10].
In computer science, the maximum subarray problem is the task of finding the contiguous subarray within a one-dimensional array of numbers which has the largest sum. For example, for the sequence of values −2, 1, −3, 4, −1, 2, 1, −5, 4; the contiguous subarray with the largest sum is 4, −1, 2, 1, with sum 6.
The problem was first posed by Ulf Grenander of Brown University in 1977, as a simplified model for maximum likelihoodestimation of patterns in digitized images. A linear time algorithm was found soon afterwards by Jay Kadane of Carnegie Mellon University (Bentley 1984).
A bit of a background: Kadane's algorithm is based on splitting up the set of possible solutions into mutually exclusive (disjoint) sets. We exploit the fact that any solution (i.e., any member of the set of solutions) will always have a last element (this is what is meant by "sum ending at position
"). Thus, we simply have to examine, one by one, the set of solutions whose last element's index is
, the set of solutions whose last element's index is
, then
, and so forth to
. It turns out that this process can be carried out in linear time.
Kadane's algorithm begins with a simple inductive question: if we know the maximum subarray sum ending at position (call this
), what is the maximum subarray sum ending at position
(equivalently, what is
)? The answer turns out to be relatively straightforward: either the maximum subarray sum ending at position
includes the maximum subarray sum ending at position
as a prefix, or it doesn't (equivalently,
, where
is the element at index
).
Thus, we can compute the maximum subarray sum ending at position for all positions
by iterating once over the array. As we go, we simply keep track of the maximum sum we've ever seen. Thus, the problem can be solved with the following code, expressed here in Python:
def max_subarray(A):
max_ending_here = max_so_far = A[0]
for x in A[1:]:
max_ending_here = max(x, max_ending_here + x)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
Note: with a bit of reasoning you will see that max_so_far is equal to .
The algorithm can also be easily modified to keep track of the starting and ending indices of the maximum subarray (when max_so_far changes) as well as the case where we want to allow zero-length subarrays (with implicit sum 0) if all elements are negative.
Because of the way this algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple/trivial example of dynamic programming.
The runtime complexity of Kadane's algorithm is .
参考自:https://en.wikipedia.org/wiki/Maximum_subarray_problem
121. Best Time to Buy and Sell Stock【easy】的更多相关文章
- 149. Best Time to Buy and Sell Stock【medium】
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
- 121. Best Time to Buy and Sell Stock (一) leetcode解题笔记
121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of ...
- 30. leetcode 121. Best Time to Buy and Sell Stock
121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of ...
- leetcode 121. Best Time to Buy and Sell Stock 、122.Best Time to Buy and Sell Stock II 、309. Best Time to Buy and Sell Stock with Cooldown
121. Best Time to Buy and Sell Stock 题目的要求是只买卖一次,买的价格越低,卖的价格越高,肯定收益就越大 遍历整个数组,维护一个当前位置之前最低的买入价格,然后每次 ...
- 121. Best Time to Buy and Sell Stock@python
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
- [LeetCode] 121. Best Time to Buy and Sell Stock 买卖股票的最佳时间
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
- 【刷题-LeetCode】121 Best Time to Buy and Sell Stock
Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a gi ...
- LeetCode OJ 121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
- 121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i. If you were ...
随机推荐
- [CF418E]Tricky Password
题意:有一个无限行$n$列的数表$a_{i,j}$,对于第$i\geq2$行,$a_{i,j}$为$a_{i-1,j}$在$a_{i-1,1\cdots j}$中出现的次数,要维护这个数表,支持修改第 ...
- maven将jar文件加入到maven库
mvn install:install-file-DgroupId=包名-DartifactId=项目名-Dversion=版本号-Dpackaging=jar-Dfile=jar文件所在路径 1,本 ...
- oop 知识点回顾
1.抽象,封装 2.继承:连接类的层次模型,并且允许类的重用,提供共性的方法,从现有的类派生(方法的重写,扩展) 派生:新类继承了基类,那么新类就是派生类,适合更合适的需要 3.多态:允许不同的类的对 ...
- iOS 获取自定义cell上按钮所对应cell的indexPath.row的方法
在UITableView或UICollectionView的自定义cell中创建一button,在点击该按钮时知道该按钮所在的cell在UITableView或UICollectionView中的行数 ...
- Easyui的numberbox无法输入以0开头的数字编号(转载)
1.问题 项目中碰到这样一个问题,Easyui的numberbox在输入数字编号的时候不能以0开头 在我输入以0开头的数字编号后,离开输入框的时候,那个前缀0就自动去掉了. 接下来,我们查看API说明 ...
- coffeescript 1.6.3使用帮助
CoffeeScript is a little language that compiles into JavaScript. Underneath that awkward Java-esque ...
- Selenium用法示例
收录待用,修改转载已取得腾讯云授权 前言 在上一节我们学习了PhantomJS 的基本用法,归根结底它是一个没有界面的浏览器,而且运行的是 JavaScript 脚本,然而这就能写爬虫了吗?这又和Py ...
- 【千纸诗书】—— PHP/MySQL二手书网站后台开发之知识点记录
前言:使用PHP和MySQL开发后台管理系统的过程中,发现有一些通用的[套路小Tip],这里集中记录一下.结合工作中ing的后台业务,我逐渐体会到:除了技术知识外.能使用户体验好的“使用流程设计”积累 ...
- Java ActiveMQ队列模式案例
创建Eclipse项目并运行 创建java project:ActiveMQ-5.14,新建lib文件夹 打开apache-activemq-5.14.0-bin\apache-activemq-5. ...
- JAVA加解密 -- 消息摘要算法
消息摘要算法是一种单向加密算法 主要用于验证数据完整性,也是数字签名的核心算法 消息鉴别:指在接收方将原始信息进行摘要,然后与接收到的摘要信息进行对比 a.MD家族 – MD5(128位摘要信息) M ...