Maximum profit of stocks

https://github.com/Premiumlab/Python-for-Algorithms--Data-Structures--and-Interviews/blob/master/Mock%20Interviews/Large%20E-Commerce%20Company/E-Commerce%20Company%20-%20Interview%20Problems%20-%20SOLUTIONS/On-Site%20Question%201%20-%20SOLUTION.ipynb

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

In [4]:

profit([10,12,14,12,13,11,8,7,6,13,23,45,11,10])

Out[4]:

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

In [11]:

# 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!

In [12]:

profit2([30,22,21,5])

Out[12]:

-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!

时间: 2024-10-01 04:33:33

Maximum profit of stocks的相关文章

HDU5052 Yaoge’s maximum profit(树链剖分)点权更新,经典题

Yaoge's maximum profit Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Total Submission(s): 662    Accepted Submission(s): 182 Problem Description Yaoge likes to eat chicken chops late at night. Yaoge has eaten to

hdu 5052 Yaoge’s maximum profit

Yaoge’s maximum profit Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 442    Accepted Submission(s): 122 Problem Description Yaoge likes to eat chicken chops late at night. Yaoge has eaten too

[Educational Round 59][Codeforces 1107G. Vasya and Maximum Profit]

咸鱼了好久...出来冒个泡_(:з」∠)_ 题目连接:1107G - Vasya and Maximum Profit 题目大意:给出\(n,a\)以及长度为\(n\)的数组\(c_i\)和长度为\(n\)的严格单调上升数组\(d_i\),求\(\max\limits_{1 \le l \le r \le n} (a\cdot(r-l+1)-\sum_{i=l}^{r}c_i-gap(l,r))\),其中\(gap(l, r) = \max\limits_{l \le i < r} (d_{i

HDU5052 Yaoge’s maximum profit(LCT)

典型的LCT操作,但是维护的是一个序列最左边减最右边的最小值,所以要维护左边减右边的最小值del[0]和一个右边减左边的最小值del[1](因为rev标记swap的时候对应的值也要交换).维护的时候del[0]可能是来自于左右儿子的del[0],也有可能是来自于左儿子的最小值减去右儿子及当前节点的值的最大值,还有就是当前节点减去右儿子的最大值,比赛的时候漏了当前节点减去右儿子的最大值因而WA了..- -0 #pragma warning(disable:4996) #include <iostr

Hdu 5052 Yaoge’s maximum profit(树链剖分)

题目大意: 给出一棵树,每个点有商店,每个商店都有一个价格,Yaoge每次从x走到y都可以在一个倒卖商品,从中得取利益,当然,买一顶要在卖之前.但是没次走过一条路,这条路上的所有商品都会增加一个v. 输出每次的最大利益. 思路分析: 很容易想到树链剖分,可是关键在于如何维护这样一个变量,使得每次都要让买的再卖的前面. 维护变量 ltr 和 rtl ,表示从左去右和从右去左. 剖分熟练的时候,判断x 和 y的深度,一步一步往上爬. 然后维护区间最大值和最小值,爬的时候更新答案. ...4921ms

HDU 5052 Yaoge’s maximum profit 裸树链剖分 2014 ACM/ICPC Asia Regional Shanghai Online

题意: 给定n个点的带点权树. 下面n行给出每个点点权表示每个点买卖鸡腿的价格 下面n-1行给出树边 下面Q个操作 Q行 u, v, val 从u走到v,过程中可以买一个鸡腿,然后到后面卖掉,输出max(0, 最大的收益) 然后给[u,v]路径上点点权+=val 思路: 树链剖分裸题 屌丝题解:点击打开链接 #pragma comment(linker, "/STACK:1024000000,1024000000") #include <cstdio> #include &

【HDU 5855】Less Time, More profit(网络流、最小割、最大权闭合子图)

Less Time, More profit Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others) Problem Description The city planners plan to build N plants in the city which has M shops. Each shop needs products from some plants to make p

[Lintcode] Best Time to Buy and Sell Stock I, II, III &amp;&amp; Maximum Subarray

买卖股票系列 && Subarray 相关题目: Best Time to Buy and Sell Stock I && II && III (IV 单独开贴) Maximum Subarray I && II 为什么这些我要总结到一起呢?因为思路基本一致. 题目简略: 买卖股票1: 一次买卖,利润最大. 买卖股票2: N次买卖,利润最大. 买卖股票3: 2次不重叠的买卖,利润最大. Maximum Subarray: Given an a

hdu-5855 Less Time, More profit(最大权闭合子图)

题目链接: Less Time, More profit Time Limit: 2000/1000 MS (Java/Others)     Memory Limit: 65536/65536 K (Java/Others) Problem Description The city planners plan to build N plants in the city which has M shops. Each shop needs products from some plants to