Sliding window max (peeked a bit)

This commit is contained in:
Dan Buch 2023-10-31 00:58:52 -04:00
parent 01a189c5ee
commit cb68a35b1b
Signed by: meatballhat
GPG Key ID: A12F782281063434
4 changed files with 39 additions and 31 deletions

File diff suppressed because one or more lines are too long

View File

@ -13,27 +13,14 @@ keywords = []
authors = [
{ name = "Dan Buch", email = "dan@meatballhat.com" },
]
classifiers = [
"Development Status :: 4 - Beta",
"Programming Language :: Python",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
]
classifiers = []
dependencies = [
"ipython",
"ipdb"
"ipdb",
"matplotlib",
"numpy"
]
[project.urls]
Documentation = "https://github.com/unknown/leetcode#readme"
Issues = "https://github.com/unknown/leetcode/issues"
Source = "https://github.com/unknown/leetcode"
[tool.hatch.envs.default]
dependencies = [
"coverage[toml]>=6.5",

View File

@ -1,4 +1,6 @@
import copy
import itertools
import math
import random
import typing
@ -538,19 +540,31 @@ def copy_random_list(
def sum_max_sub_array(nums: list[int]) -> int:
window_size: int = 1
begin: int = 0
end: int = window_size
max_sum: int = sum(nums)
mmax = last = prev = nums[0]
while end - begin <= len(nums):
while end <= len(nums):
max_sum = max(max_sum, sum(nums[begin:end]))
begin += 1
end += 1
for i in range(1, len(nums)):
prev = nums[i] + last
last = max(nums[i], prev)
mmax = max(mmax, last)
window_size += 1
begin = 0
end = window_size
return mmax
return max_sum
def sum_max_sub_array_accum(nums: list[int]) -> int:
accum: list[int] = [nums[0]]
for i in range(1, len(nums)):
prev: int = nums[i] + accum[-1]
accum.append(max(nums[i], prev))
return max(accum)
def accum_sub_array_maxes(nums: list[int]) -> list[int]:
accum: list[int] = [nums[0]]
for i in range(1, len(nums)):
prev: int = nums[i] + accum[-1]
accum.append(max(nums[i], prev))
return accum

View File

@ -1,3 +1,5 @@
import json
import pytest
import stuff
@ -465,7 +467,11 @@ def test_trie_busy():
[-2, 1],
1,
),
(
json.load(open(".testdata/max_sub_array0.json")),
11081,
),
],
)
def test_maximum_subarray(nums: list[int], expected: int):
def test_max_sub_array(nums: list[int], expected: int):
assert stuff.sum_max_sub_array(nums) == expected