"This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges)."
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"# Solution Notebook"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Problem: Given a list of stock prices, find the max profit from 1 buy and 1 sell.\n",
"\n",
"* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n",
"* [Algorithm](#Algorithm)\n",
"* [Code](#Code)\n",
"* [Unit Test](#Unit-Test)"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Constraints\n",
"\n",
"* Are all prices positive ints?\n",
" * Yes\n",
"* Is the output an int?\n",
" * Yes\n",
"* If profit is negative, do we return the smallest negative loss?\n",
" * Yes\n",
"* If there are less than two prices, what do we return?\n",
" * Exception\n",
"* Can we assume the inputs are valid?\n",
" * No\n",
"* Can we assume this fits memory?\n",
" * Yes"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Test Cases\n",
"\n",
"* None -> TypeError\n",
"* Zero or one price -> ValueError\n",
"* No profit\n",
" * [8, 5, 3, 2, 1] -> -1\n",
"* General case\n",
" * [5, 3, 7, 4, 2, 6, 9] -> 7"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Algorithm\n",
"\n",
"We'll use a greedy approach and iterate through the prices once.\n",
"\n",
"* Loop through the prices\n",
" * Update current profit (price = min_price)\n",
" * Update the min price\n",
" * Update the max profit\n",
"* Return max profit\n",
"\n",
"Complexity:\n",
"* Time: O(n)\n",
"* Space: O(1)"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Code"
]
},
{
"cell_type":"code",
"execution_count":1,
"metadata":{
"collapsed":false
},
"outputs":[],
"source":[
"import sys\n",
"\n",
"\n",
"class Solution(object):\n",
"\n",
" def find_max_profit(self, prices):\n",
" if prices is None:\n",
" raise TypeError('prices cannot be None')\n",
" if len(prices) < 2:\n",
" raise ValueError('prices must have at least two values')\n",