From c717f8d86091011013d4731a91161143fa61b7d7 Mon Sep 17 00:00:00 2001 From: Taufik Algi F <43858377+taufikalgi@users.noreply.github.com> Date: Fri, 1 Nov 2019 00:45:01 +0700 Subject: [PATCH] add max sum contigous subsequence (#1537) * add max sum contigous subsequence * fix typo * Add doctest and type hints * Create autoblack.yml --- .github/workflows/autoblack.yml | 34 +++++++++++++++++++ .../max_sum_contigous_subsequence.py | 20 +++++++++++ 2 files changed, 54 insertions(+) create mode 100644 .github/workflows/autoblack.yml create mode 100644 dynamic_programming/max_sum_contigous_subsequence.py diff --git a/.github/workflows/autoblack.yml b/.github/workflows/autoblack.yml new file mode 100644 index 000000000..98310ac80 --- /dev/null +++ b/.github/workflows/autoblack.yml @@ -0,0 +1,34 @@ +# GitHub Action that uses Black to reformat the Python code in an incoming pull request. +# If all Python code in the pull request is complient with Black then this Action does nothing. +# Othewrwise, Black is run and its changes are committed back to the incoming pull request. +# https://github.com/cclauss/autoblack + +name: autoblack +on: [pull_request] +jobs: + build: + runs-on: ubuntu-latest + strategy: + max-parallel: 1 + matrix: + python-version: [3.7] + steps: + - uses: actions/checkout@v1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v1 + with: + python-version: ${{ matrix.python-version }} + - name: Install psf/black + run: pip install black + - name: Run black --check . + run: black --check . + - name: If needed, commit black changes to the pull request + if: failure() + run: | + black . + git config --global user.name 'autoblack' + git config --global user.email 'cclauss@users.noreply.github.com' + git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY + git checkout $GITHUB_HEAD_REF + git commit -am "fixup: Format Python code with psf/black" + git push diff --git a/dynamic_programming/max_sum_contigous_subsequence.py b/dynamic_programming/max_sum_contigous_subsequence.py new file mode 100644 index 000000000..2cbdb97a1 --- /dev/null +++ b/dynamic_programming/max_sum_contigous_subsequence.py @@ -0,0 +1,20 @@ +def max_subarray_sum(nums: list) -> int: + """ + >>> max_subarray_sum([6 , 9, -1, 3, -7, -5, 10]) + 17 + """ + if not nums: + return 0 + n = len(nums) + s = [0] * n + res, s, s_pre = nums[0], nums[0], nums[0] + for i in range(1, n): + s = max(nums[i], s_pre + nums[i]) + s_pre = s + res = max(res, s) + return res + + +if __name__ == "__main__": + nums = [6, 9, -1, 3, -7, -5, 10] + print(max_subarray_sum(nums))