{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Contiguous Subarray\n", "Largest Sum Contiguous Subarray" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Kadane's Algorithm - Dynamic Programming - O(n)" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def largeSumContiguousSubArr(arr):\n", " start, end = 0, 0\n", " s = 0\n", " max_so_far, curr_max = 0, 0\n", " \n", " for i in range(len(arr)):\n", " curr_max += arr[i]\n", " \n", " if curr_max < 0:\n", " curr_max = 0\n", " s = i + 1\n", " elif curr_max > max_so_far:\n", " max_so_far = curr_max\n", " start = s\n", " end = i\n", " \n", " return arr[start : end + 1], max_so_far" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[-2, -3, 4, -1, -2, 1, 5, -3]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr = [-2, -3, 4, -1, -2, 1, 5, -3]\n", "arr" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "([4, -1, -2, 1, 5], 7)" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "largeSumContiguousSubArr(arr)" ] } ], "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.6.2" } }, "nbformat": 4, "nbformat_minor": 2 }