Skip to content

Commit 8d8292b

Browse files
author
Mauricio Klein
committed
Add solution for challenge #36
1 parent 95035e7 commit 8d8292b

File tree

6 files changed

+47
-0
lines changed

6 files changed

+47
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,4 @@
3535
- [x] [Challenge 33: Merge Overlapping Intervals](challenge-33/)
3636
- [x] [Challenge 34: Subset sum problem](challenge-34/)
3737
- [x] [Challenge 35: Count rectangles](challenge-35/)
38+
- [x] [Challenge 36: Maximum Profit From Stocks](challenge-36/)

Diff for: challenge-36/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

Diff for: challenge-36/README.md

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Maximum Profit From Stocks
2+
3+
This problem was recently asked by Apple.
4+
5+
## Description
6+
7+
You are given an array. Each element represents the price of a stock on that particular day.
8+
9+
Calculate and return the maximum profit you can make from buying and selling that stock only once.
10+
11+
## Example
12+
13+
```
14+
Input: (9, 11, 8, 5, 7, 10)
15+
Output: 5 (Buy on "5" and sell on "10")
16+
```

Diff for: challenge-36/__init__.py

Whitespace-only changes.

Diff for: challenge-36/solver.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
#
2+
# Time complexity: O(n)
3+
# Space complexity: O(1)
4+
#
5+
def buy_and_sell(prices):
6+
min_price = float('inf')
7+
max_profit = 0
8+
9+
for price in prices:
10+
min_price = min(min_price , price )
11+
max_profit = max(max_profit, price - min_price)
12+
13+
return max_profit

Diff for: challenge-36/test_solver.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import unittest
2+
from solver import buy_and_sell
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_buy_and_sell(self):
6+
self.assertEqual(buy_and_sell((9, 11, 8, 5, 7, 10)), 5) # Buy on "5" and sell on "10"
7+
self.assertEqual(buy_and_sell((9, 11, 5, 2, 6, 6 )), 4) # Buy on "2" and sell on "6"
8+
self.assertEqual(buy_and_sell((4, 4, 4, 4 )), 0) # Buy and sell for the same price
9+
self.assertEqual(buy_and_sell((4, 3, 2, 1 )), 0) # Lost money: profit zero
10+
self.assertEqual(buy_and_sell(( )), 0)
11+
12+
if __name__ == "__main__":
13+
unittest.main()

0 commit comments

Comments
 (0)