Maximum profit of stocks
On-Site Question 1 - SOLUTION
Problem
You've been given a list of historical stock prices for a single day for Amazon stock. The index of the list represents the timestamp, so the element at index of 0 is the initial price of the stock, the element at index 1 is the next recorded price of the stock for that day, etc. Your task is to write a function that will return the maximum profit possible from the purchase and sale of a single share of Amazon stock on that day. Keep in mind to try to make this as efficient as possible.
For example, if you were given the list of stock prices:
prices = [12,11,15,3,10]
Then your function would return the maximum possible profit, which would be 7 (buying at 3 and selling at 10).
Requirements
Try to solve this problem with paper/pencil first without using an IDE. Also keep in mind you should be able to come up with a better solution than just brute forcing every possible sale combination
Also you can't "short" a stock, you must buy before you sell the stock.
Solution
Let's think about a few things before we start coding. One thing to think about right off the bat is that we can't just find the maximum price and the lowest price and then subtract the two, because the max could come before the min.
The brute force method would be to try every possible pair of price combinations, but this would be O(N^2), pretty bad. Also since this is an interview setting you should probably already know that there is a smarter solution.
In this case we will use a greedy algorithm approach. We will iterate through the list of stock prices while keeping track of our maximum profit.
That means for every price we will keep track of the lowest price so far and then check if we can get a better profit than our current max.
Let's see an implementation of this:
def profit(stock_prices):
# Start minimum price marker at first price
min_stock_price = stock_prices[0]
# Start off with a profit of zero
max_profit = 0
for price in stock_prices:
# Check to set the lowest stock price so far
min_stock_price = min(min_stock_price,price)
# Check the current price against our minimum for a profit
# comparison against the max_profit
comparison_profit = price - min_stock_price
# Compare against our max_profit so far
max_profit = max(max_profit,comparison_profit)
return max_profit
profit([10,12,14,12,13,11,8,7,6,13,23,45,11,10])
39
Currently we're finding the max profit in one pass O(n) and in constant space O(1). However, we still aren't thinking about any edge cases. For example, we need to address the following scenarios:
- Stock price always goes down
- If there's less than two stock prices in the list.
We can take care of the first scenario by returning a negative profit if the price decreases all day (that way we can know how much we lost). And the second issue can be solved with a quick len() check. Let's see the full solution:
def profit2(stock_prices):
# Check length
if len(stock_prices) < 2:
raise Exception('Need at least two stock prices!')
# Start minimum price marker at first price
min_stock_price = stock_prices[0]
# Start off with an initial max profit
max_profit = stock_prices[1] - stock_prices[0]
# Skip first index of 0
for price in stock_prices[1:]:
# NOTE THE REORDERING HERE DUE TO THE NEGATIVE PROFIT TRACKING
# Check the current price against our minimum for a profit
# comparison against the max_profit
comparison_profit = price - min_stock_price
# Compare against our max_profit so far
max_profit = max(max_profit,comparison_profit)
# Check to set the lowest stock price so far
min_stock_price = min(min_stock_price,price)
return max_profit
# Exception Raised
profit2([1])
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-11-7bd2f0c7e63b> in <module>()
1 # Exception Raised
----> 2 profit2([1]) <ipython-input-10-e06adf3c45a7> in profit2(stock_prices)
3 # Check length
4 if len(stock_prices) < 2:
----> 5 raise Exception('Need at least two stock prices!')
6
7 # Start minimum price marker at first price Exception: Need at least two stock prices!
profit2([30,22,21,5])
-1
Great! Now we can prepare for worst case scenarios. Its important to keep edge cases in mind, especially if you are able to solve the original question fairly quickly.
Good Job!
Maximum profit of stocks的更多相关文章
- [Educational Round 59][Codeforces 1107G. Vasya and Maximum Profit]
咸鱼了好久...出来冒个泡_(:з」∠)_ 题目连接:1107G - Vasya and Maximum Profit 题目大意:给出\(n,a\)以及长度为\(n\)的数组\(c_i\)和长度为\( ...
- Yaoge’s maximum profit HDU - 5052
Yaoge’s maximum profit Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/ ...
- Maximum Profit
Maximum Profit You can obtain profits from foreign exchange margin transactions. For example, if you ...
- Codeforces 1107G Vasya and Maximum Profit 线段树最大子段和 + 单调栈
Codeforces 1107G 线段树最大子段和 + 单调栈 G. Vasya and Maximum Profit Description: Vasya got really tired of t ...
- 【leetcode】1235. Maximum Profit in Job Scheduling
题目如下: We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtai ...
- HDU5052 Yaoge’s maximum profit(LCT)
典型的LCT操作,但是维护的是一个序列最左边减最右边的最小值,所以要维护左边减右边的最小值del[0]和一个右边减左边的最小值del[1](因为rev标记swap的时候对应的值也要交换).维护的时候d ...
- HDU 5052 Yaoge’s maximum profit 光秃秃的树链拆分 2014 ACM/ICPC Asia Regional Shanghai Online
意甲冠军: 特定n小点的树权. 以下n每一行给出了正确的一点点来表达一个销售点每只鸡价格的格 以下n-1行给出了树的侧 以下Q操作 Q行 u, v, val 从u走v,程中能够买一个鸡腿,然后到后面卖 ...
- codeforces1107G Vasya and Maximum Profit 【模拟】
题目分析: 前缀和啥的模拟一下就行了. 代码: #include<bits/stdc++.h> using namespace std; ; int n,x,d[maxn],sta[max ...
- Codeforces 1107G Vasya and Maximum Profit [单调栈]
洛谷 Codeforces 我竟然能在有生之年踩标算. 思路 首先考虑暴力:枚举左右端点直接计算. 考虑记录\(sum_x=\sum_{i=1}^x c_i\),设选\([l,r]\)时那个奇怪东西的 ...
随机推荐
- 23.OGNL与ValueStack(VS)-调用普通类的构造方法
转自:https://wenku.baidu.com/view/84fa86ae360cba1aa911da02.html 建立一个新的类:Student,在此省略代码. 然后在loginSuc.js ...
- input文本框 放上图片img 通过padding relative和absolute 的实现
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- c++实现一个比较两个string类型的版本号的小demo
在软件实现更新模块的时候,有可能会判断一下服务器上的版本的版本号和本地版本的版本号. 下面有类似这样形式的版本号:string str = "0.0.0.1"; 分析一下可以看出, ...
- Git----分支管理之bug分支04
---恢复内容开始--- 软件开发中,bug就像家常便饭一样,有了bug就需要修复,在Git中,由于分支是如此强大,所以,每个bug都可以通过一个临时分支来修复,修复后,合并分支,然后将临时分支删除. ...
- vue-cli 上手
1.cnpm install --global vue-cli 安装脚手架 2.vue init webpack baoge 创建 3.选择配置项 Project name (baoge): ---- ...
- Gulp的安装与配置
http://blog.csdn.net/itlsx/article/details/49981459
- sqlserver查询自定义的函数
1)sp_helptext同样适应用自定义函数 2)sys.sql_modules表也可以查 查看函数的源代码: exec sp_helptext '函数名'
- Haskell语言学习笔记(39)Category
Category class Category cat where id :: cat a a (.) :: cat b c -> cat a b -> cat a c instance ...
- JAVA中会存在内存泄露吗
所谓内存泄露就是指一个不再被程序使用的对象或变量一直被占据在内存中.java中有垃圾回收机制,它可以保证一对象不再被引用的时候,即对象编程了孤儿的时候,对象将自动被垃圾回收器从内存中清除掉.由于Jav ...
- linux 批量删除文件名中有换行符
ls -i | grep ^M | awk '{print $1}' | xargs -t -I [] find . -inum [] -exec rm -if {} \; 注意^M 是ctrl+v ...