This notebook was prepared by Donne Martin. Source and license info is on GitHub.
We'll use a greedy approach and iterate through the prices once.
Complexity:
import sys
class Solution(object):
def find_max_profit(self, prices):
if prices is None:
raise TypeError('prices cannot be None')
if len(prices) < 2:
raise ValueError('prices must have at least two values')
min_price = prices.pop(0)
max_profit = prices[0] - min_price
for price in prices:
profit = price - min_price
min_price = min(price, min_price)
max_profit = max(profit, max_profit)
return max_profit
%%writefile test_max_profit.py
import unittest
class TestMaxProfit(unittest.TestCase):
def test_max_profit(self):
solution = Solution()
self.assertRaises(TypeError, solution.find_max_profit, None)
self.assertRaises(ValueError, solution.find_max_profit, [])
self.assertEqual(solution.find_max_profit([8, 5, 3, 2, 1]), -1)
self.assertEqual(solution.find_max_profit([5, 3, 7, 4, 2, 6, 9]), 7)
print('Success: test_max_profit')
def main():
test = TestMaxProfit()
test.test_max_profit()
if __name__ == '__main__':
main()
Overwriting test_max_profit.py
%run -i test_max_profit.py
Success: test_max_profit