Compare commits

...

4 Commits

Author SHA1 Message Date
db38eeada9
One more thought about max sub-array 2023-10-31 08:00:18 -04:00
cb68a35b1b
Sliding window max (peeked a bit) 2023-10-31 00:58:52 -04:00
01a189c5ee
Yet Another Off By One Error 2023-10-28 08:24:17 -04:00
3580198513
Max sub-array slidey window 2023-10-28 08:21:39 -04:00
4 changed files with 82 additions and 17 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
@ -535,3 +537,47 @@ def copy_random_list(
ordered_copy[i].random = ordered_copy[hash_idx[hash(entry.random)]]
return ordered_copy[0]
def sum_max_sub_array(nums: list[int]) -> int:
mmax = last = prev = nums[0]
for i in range(1, len(nums)):
prev = nums[i] + last
last = max(nums[i], prev)
mmax = max(mmax, last)
return mmax
def sum_max_sub_array_i(nums: list[int]) -> tuple[int, int]:
mmax_i: int = 0
mmax = last = prev = nums[0]
for i in range(1, len(nums)):
prev = nums[i] + last
last = max(nums[i], prev)
mmax_i = i if last > mmax else mmax_i
mmax = max(mmax, last)
return mmax_i, mmax
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
@ -444,3 +446,32 @@ def test_trie_busy():
assert trie.startsWith("rent") is True
assert trie.startsWith("beer") is True
assert trie.startsWith("jam") is True
@pytest.mark.parametrize(
("nums", "expected"),
[
(
[-2, 1, -3, 4, -1, 2, 1, -5, 4],
6,
),
(
[1],
1,
),
(
[5, 4, -1, 7, 8],
23,
),
(
[-2, 1],
1,
),
(
json.load(open(".testdata/max_sub_array0.json")),
11081,
),
],
)
def test_max_sub_array(nums: list[int], expected: int):
assert stuff.sum_max_sub_array(nums) == expected