0% found this document useful (0 votes)
53 views

Python leetcode solution 4

Uploaded by

Biji CL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views

Python leetcode solution 4

Uploaded by

Biji CL
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Creative Work

Best Time to Buy


and Sell Stocks
Rupaak S (22BCE0347)
Problem Statement

High-level details
More Details…
Overview
The input given is an array where
each element represents the price
of a stock on that particular day, for
example, prices[0] represent the
price of the stock on the first day,
prices[1] represent the price of the

Overview
stock on the second day and so on.
Points to remember:
• You can only make one
transaction
• Only one stock is allowed to be
bought or sold
• You can only sell after buying
Example 1
The input is [7,1,5,3,6,4] , to make
the maximum profit we buy one
stock on the second day with the

Background
cost of 1 and sell it on the 5th day
with a price of 6, making a profit of
(6-1 = 5) 5.
Example 2:
The input given here [7, 6, 4, 3, 2, 1] ,
You can notice that the prices are
always decreasing, It doesn't

Background
matter on which day we buy or sell
we will always make a negative
profit, that is a loss. So the greatest
profit we can make is when we do
no transactions, 0 profit. So we
return 0.
Example 2:
The input given here [7, 6, 4, 3, 2, 1] ,
You can notice that the prices are
always decreasing, It doesn't

Background
matter on which day we buy or sell
we will always make a negative
profit, that is a loss. So the greatest
profit we can make is when we do
no transactions, 0 profit. So we
return 0.
Any Ideas ?
Attempt 1
This is a trivial solution where we are using two
nested for loops to find the maximum profit
between two days, the outer for loop iterates
through the array and returns the value and the
index of the current element using enumerate
function, the inner for loop slices the array from
the current element till the last element. And

Attempt 1
profit is equal to max of the current profit and
the profit between the two days in the loop.

We are just looking for the maximum price of


the stock to the right of the buying day, and then
the profit is passed through the max function to
find the maximum profit, and return it.
Time Limit Exceeded
This solution has passed 198/211
test cases, which means that the
code is probably right, but it is not

The Challenge
the most optimal solution
You can the test case that it failed,
it starts from 10000 and goes all
the way to 0 in descending order
and the price of the stock
continues to be 0 until the length of
the array is 26004
Attempt 2
Since the test case we failed was in descending
order and the profit is 0, I thought that sorting

Attempt 2
the array prices and comparing it with the
original array will tell us if the prices are always
descending, considering the sort(function) is
faster than the nested loops
Time Limit Exceeded

The Challenge
Time limit error, 198/211 test cases
checked and passed, the code is
still not the most optimal solution
Other Trivial Attempt:
The big O notation:
“Big O notation is a mathematical notation that describes the
limiting behavior of a function when the argument tends towards a
particular value or infinity. It is a member of a family of notations

The Big O notation


invented by Paul Bachmann, Edmund Landau, and others,
collectively called Bachmann–Landau notation or asymptotic
notation.”

— Wikipedia’s definition of Big O notation

In basic words, the Big O notation tells us about the time complexity of a
given operation or a function of a code in terms of algebraic terms.
The big O notation:

To understand what Big O notation is, we can take a look at a typical


example, O(n²), which is usually pronounced: “Big O squared”.

The Big O notation


The letter “n” here represents the input size, and the function “g(n) = n²”
inside the “O( )” gives us an idea of how complex the algorithm is with
respect to the input size.

O(1/n) < O(log n) < O(n) < O(n log n) < O(n²) < O(2^n) < O(n!)​
The big O notation:
Accessing an array is O(1)
​Iterating through an array once is O(n),
Iterating through an array twice in a nested manner is O(n²)

The Big O notation


Finding the all possible combinations is O(n!)
Insertion and Deletion of an element is O(n)

a=[1,2,3,4,5,6,7,8] a=[1,2,3,4,5,6,7,8]
target=6 for i in a:
for i in a: if i==8:
for j in a: return True
if i+j==6:
return i,j
The big O notation:
The time complexity of the above function is
O(n^2).The outer for loop has a time
complexity of O(n), as it iterates through the

The Big O notation


list prices of length n. The inner for loop also
has a time complexity of O(n), as it iterates
through a sublist of prices starting from the
current index of the outer loop. The length of this sublist is equal to the remaining
number of elements in the list, which is also n.

Therefore, the overall time complexity of the function is O(n * n) = O(n^2). This means
that the running time of the function grows quadratically with the size of the input list.
The challenge
Optimising the Code:

So the challenge is to make the code more time efficient, the most optimal solution will
be O(n)

The Challenge
This means that we should iterate through the array only once, and return the maximum
profit than can be made with one transaction.

So I completely gave up on the previous


logic and started searching for a better
one
Going back to the drawing board:
8
7

6
6

Start Again
5

4
4
I plotted a graph with the prices on
3
the y-axis and the days on the x-axis
to better understand how to solve
2
the code better 1

0
1 2 3 4 5 6
Going back to the drawing board:
8
7

6
6

Start Again
5

4
4
I plotted a graph with the prices on
3
the y-axis and the days on the x-axis
to better understand how to solve
2
the code better 1

0
1 2 3 4 5 6
Two Pointer Approach (Algorithm):
• We initialise two variables left and right with values 0 and 1, the pointer
point to the index of the array

Two Pointer Approach


• If the value of the stock on the right point is greater than the value of the
stock at the left pointer we add we assign the value of the profit to a
variable current profit
• If the value at the right is less than the value at the left, we won't make any
transaction, we bring both the left and right pointer together, because it is
the new minima, and we increase the right pointer by a value of 1 to check
if we can make a higher profit.
• When we reach the end of the array 'prices', we return the value of the
current profit, which is the highest profit we can make with one
transaction
Two Pointer Approach (In Working):
8
7 First, we assign two pointers or two
6 variables which point to the index of the
6

Two Pointer Approach


5 array list
4
4 left=0
3
right=1
2 • Day -1: The left pointer points at the 0
1
index of the array whose value is 7 , the
0 right pointer points at the 1st index with
1 2 3 4 5 6
the value 1, since the value of right is
less than left we won't do any
transaction, we assign left=1 and
right+=1
Two Pointer Approach (In Working):
8
7 • Day -2: Now the right pointer points to
6 the value 5 and the left to the value 1,
6

Two Pointer Approach


5 the right is greater than the left so we
4
4 buy the stock with the value 1, the
3
current profit is (5-1) 4, right+=1
2 • Day - 3: The right pointer points to the
1
value 3, the left to the value 1, If you sell
0 the stock on day 4, we get a profit of 3,
1 2 3 4 5 6
which is less than if we would sell it on
day 3 with a profit 4, so we won't do
anything, right+=1
Two Pointer Approach (In Working):
8
7 • Day -2: Now the right pointer points to
6 the value 5 and the left to the value 1,
6

Two Pointer Approach


5 the right is greater than the left so we
4
4 buy the stock with the value 1, the
3
current profit is (5-1) 4, right+=1
2 • Day - 3: The right pointer points to the
1
value 3, the left to the value 1, If you sell
0 the stock on day 4, we get a profit of 3,
1 2 3 4 5 6
which is less than if we would sell it on
day 3 with a profit 4, so we won't do
anything, right+=1
Two Pointer Approach (In working):
8 • Day -4: The right pointer points to the
7
6 value of 6, which is greater than the
6
value of 1, if we sell the stock on day 5,

Two Pointer Approach


5
4 the profit would be 6-1 = 5, which is
4
3 greater than the previous profit of 4, so
the current profit is 5, right+=1
2
1 • Day - 5: The right pointer now points at
the value of 4, which is still greater than
0
1 2 3 4 5 6 the value of the left pointer 1, so we
won't do anything, since we reached the
end of the array, we return the value of
the current profit which is 6, we buy on
day 2 and sell on day 5.
Two Pointer Approach (In Working):
8 • Day -4: The right pointer points to the
7
6 value of 6, which is greater than the
6
value of 1, if we sell the stock on day 5,

Two Pointer Approach


5
4 the profit would be 6-1 = 5, which is
4
3 greater than the previous profit of 4, so
the current profit is 5, right+=1
2
1 • Day - 5: The right pointer now points at
the value of 4, which is still greater than
0
1 2 3 4 5 6 the value of the left pointer 1, so we
won't do anything, since we reached the
end of the array, we return the value of
the current profit which is 6, we buy on
day 2 and sell on day 5.
Attempt 3
Two Pointer Approach (Code):
Result
Buy and Sell Stock II
A modified version of the previous problem
Problem Statement

Problem Statement
High-level details
Overview
The input given is an array where
each element represents the price
of a stock on that particular day, for
example, prices[0] represent the
price of the stock on the first day,
prices[1] represent the price of the

Overview
stock on the second day and so on.
Points to remember:
• You can make any number of
transactions
• Only one stock is allowed to be
bought or sold
• You can only sell after buying
Example 1
The input is [7,1,5,3,6,4] , to make the most
profit, we buy on day 2 at the price of 1 and
sell on day 3 for the price of 5 with a profit of
4, we again buy on day 4 at the price 3 and
sell it on day 5 with the price of 6, bringing

Example Testcases
the total profit to 7

Example 2
The input is [1,2,3,4,5], to make the most
profit we buy the stock on day 1 at another
price of 1, and sell it on day 5 at the price of
5 making a total profit of 4
Note: Here even if you buy and sell the stock
every other day you will get the profit of 4
Example 1
Here the input is [ 7, 6, 4, 3, 1] , the prices are
always decreasing, so we cannot make any
profit, the best case is making 0 profit, so we

Example Testcases
return 0

Constraints

• 1 <= prices.length <= 3 * 10^4

• 0 <= prices[ i ] <= 104


Any Ideas ?
8
7 • We have to find the maximum
6 profit over the whole array,
6
5 making any number of
4 transactions.
4
3
• To make the most profit, we
buy at every local minimum

Explanation
2 and sell at every local
1
maximum
0
1 2 3 4 5 6

• In the above graph, we buy on • Instead of finding the maxima and the
days 2 and 4 and sell the minima, we can just check if the prices are
stocks on days 3 and 5 increasing and add the profit to the total
profit on each day
Code :
• We initialise the variables total_profit, left,
right with the values 0,0,1, respectively
• While right is not at the end of the array, if
the value of the stock at the right pointer

Phase 1
is greater than the value of the left pointer,
it means that the price is increasing, so we
add the difference to the total_profit
• If the price of the left pointer is greater than the price of the right pointer, the price is
decreasing, we won't do any transaction in that case
• Increase both left and right by 1, and continue the loop, until after the the right pointer
points to the last element
Result :

Result
Better Code :

Better Code
Credits :

• Wikepedia • Freecodecamp.org • leetcode • pitch.io


Thank you

You might also like