Teaching Kids Programming – Best Time to Buy and Sell Stock (Buy and Sell Once – Three Algorithms)


Teaching Kids Programming: Videos on Data Structures and Algorithms

You are given an array prices where prices[i] is the price of a given stock on the ith day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Best Time to Buy and Sell Stock via Bruteforce Algorithm

We can bruteforce the day to Buy and Sell the stock. This takes O(N^2) time.

1
2
3
4
5
6
7
8
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        ans = 0
        for i in range(n):
            for j in range(i + 1, n):
                ans = max(ans, prices[j] - prices[i])
        return ans     
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        n = len(prices)
        ans = 0
        for i in range(n):
            for j in range(i + 1, n):
                ans = max(ans, prices[j] - prices[i])
        return ans     

One Pass Linear Algorithm to Track the Lowest

A better approach is to remember the lowest price that we have seen and compute the profit if sold on the day.

1
2
3
4
5
6
7
8
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        low = math.inf
        ans = 0
        for i in prices:
            low = min(low, i)
            ans = max(i - low, ans)
        return ans
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        low = math.inf
        ans = 0
        for i in prices:
            low = min(low, i)
            ans = max(i - low, ans)
        return ans

Time complexity is O(N) and we are using O(1) constant space.

Transformed to Maximum Subarray Sum and then Apply Kadane’s Algorithm

Given the prices array tex_70b3412d247fdddcda8def70ff17967e Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video and the B array is the difference array, where tex_433141991f6e1382595e96b7a1202355 Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video and tex_0277a4177e97200855e31a29a7d887a4 Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video if i not equal to zero.

tex_8cc8dd05885c3b070f34cc93316f532f Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video
tex_3643f520f3ddf5f3c3343ef3376293ef Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video
tex_7864ae744dfbedc0e8466083a5a870eb Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video

If the lowest point is at a2, and the highest point after a2 is at a5, the max profit we can get is tex_fc2f0fa07b86f81976ce350a1ede0e42 Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video , which is the same as tex_d21588cac5a120d09903e6f2bca811f2 Teaching Kids Programming - Best Time to Buy and Sell Stock (Buy and Sell Once - Three Algorithms) algorithms math python teaching kids programming youtube video i.e. we need to find the maximum sum of subarray – and we can use Kadane’s algorithm.

1
2
3
4
5
6
7
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        ans = cur = 0
        for i in range(1, len(prices)):
            cur = max(0, cur + prices[i] - prices[i - 1])
            ans = max(ans, cur)
        return ans
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        ans = cur = 0
        for i in range(1, len(prices)):
            cur = max(0, cur + prices[i] - prices[i - 1])
            ans = max(ans, cur)
        return ans

Linear time complexity O(N) as we need to go through the array once. And we need a constant time space O(1).

Buy and Sell Stock Algorithms

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
946 words
Last Post: Teaching Kids Programming - Tower of Hanoi via Recursion (Math Induction Proof of Minimal Number of Moves)
Next Post: Teaching Kids Programming - Restore the Word from Rules

The Permanent URL is: Teaching Kids Programming – Best Time to Buy and Sell Stock (Buy and Sell Once – Three Algorithms)

Leave a Reply