Add max profit challenge

This commit is contained in:
Donne Martin 2017-03-29 04:32:22 -04:00
parent f2587dc29b
commit d28febfded
4 changed files with 403 additions and 0 deletions

View File

View File

@ -0,0 +1,175 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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": [
"# Challenge 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",
"See the [LeetCode](https://leetcode.com/problems/) problem page.\n",
"\n",
"* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n",
"* [Algorithm](#Algorithm)\n",
"* [Code](#Code)\n",
"* [Unit Test](#Unit-Test)\n",
"* [Solution Notebook](#Solution-Notebook)"
]
},
{
"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",
"Refer to the [Solution Notebook](). If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Code"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class Solution(object):\n",
"\n",
" def find_max_profit(self, prices):\n",
" # TODO: Implement me\n",
" pass"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**The following unit test is expected to fail until you solve the challenge.**"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# %load test_max_profit.py\n",
"from nose.tools import assert_equal, assert_raises\n",
"\n",
"\n",
"class TestMaxProfit(object):\n",
"\n",
" def test_max_profit(self):\n",
" solution = Solution()\n",
" assert_raises(TypeError, solution.find_max_profit, None)\n",
" assert_raises(ValueError, solution.find_max_profit, [])\n",
" assert_equal(solution.find_max_profit([8, 5, 3, 2, 1]), -1)\n",
" assert_equal(solution.find_max_profit([5, 3, 7, 4, 2, 6, 9]), 7)\n",
" print('Success: test_max_profit')\n",
"\n",
"\n",
"def main():\n",
" test = TestMaxProfit()\n",
" test.test_max_profit()\n",
"\n",
"\n",
"if __name__ == '__main__':\n",
" main()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Solution Notebook\n",
"\n",
"Review the [Solution Notebook]() for a discussion on algorithms and code solutions."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.0"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@ -0,0 +1,207 @@
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"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",
" min_price = prices[0]\n",
" max_profit = -sys.maxsize\n",
" for index, price in enumerate(prices):\n",
" if index == 0:\n",
" continue\n",
" profit = price - min_price\n",
" min_price = min(price, min_price)\n",
" max_profit = max(profit, max_profit)\n",
" return max_profit"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Unit Test"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting test_max_profit.py\n"
]
}
],
"source": [
"%%writefile test_max_profit.py\n",
"from nose.tools import assert_equal, assert_raises\n",
"\n",
"\n",
"class TestMaxProfit(object):\n",
"\n",
" def test_max_profit(self):\n",
" solution = Solution()\n",
" assert_raises(TypeError, solution.find_max_profit, None)\n",
" assert_raises(ValueError, solution.find_max_profit, [])\n",
" assert_equal(solution.find_max_profit([8, 5, 3, 2, 1]), -1)\n",
" assert_equal(solution.find_max_profit([5, 3, 7, 4, 2, 6, 9]), 7)\n",
" print('Success: test_max_profit')\n",
"\n",
"\n",
"def main():\n",
" test = TestMaxProfit()\n",
" test.test_max_profit()\n",
"\n",
"\n",
"if __name__ == '__main__':\n",
" main()"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Success: test_max_profit\n"
]
}
],
"source": [
"%run -i test_max_profit.py"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.5.0"
}
},
"nbformat": 4,
"nbformat_minor": 0
}

View File

@ -0,0 +1,21 @@
from nose.tools import assert_equal, assert_raises
class TestMaxProfit(object):
def test_max_profit(self):
solution = Solution()
assert_raises(TypeError, solution.find_max_profit, None)
assert_raises(ValueError, solution.find_max_profit, [])
assert_equal(solution.find_max_profit([8, 5, 3, 2, 1]), -1)
assert_equal(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()