Skip to content

Add Max Fenwick Tree #6298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Aug 12, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fix type hints
  • Loading branch information
itsamirhn committed Aug 6, 2022
commit a3910c5f21cfe2fdd309f816cdd82ed8da307f60
32 changes: 16 additions & 16 deletions data_structures/binary_tree/maximum_fenwick_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,31 +16,31 @@ class MaxFenwickTree:
10
"""

def __init__(self, n: int): # Create Fenwick tree with size n
def __init__(self, n: int) -> None: # Create Fenwick tree with size n
self.n = n
self.arr = [0] * (n + 1)
self.tree = [0] * (n + 1)

def update(
self, i, val
) -> None: # Set value of index i (1-Based) to val in O(lg^2 N)
self.arr[i] = val
while i < self.n:
self.tree[i] = max(val, self.query(i, i - i & -i))
i += i & (-i)
self, index: int, value: int
) -> None: # Set index (1-Based) to value in O(lg^2 N)
self.arr[index] = value
while index < self.n:
self.tree[index] = max(value, self.query(index, index - index & -index))
index += index & (-index)

def query(
self, l, r
) -> int: # Query maximum value from range (l, r] (1-Based) in O(lg N)
self, left: int, right: int
) -> int: # Query maximum value from range (left, right] (1-Based) in O(lg N)
res = 0
while l < r:
ll = r - r & -r
if l < ll:
res = max(res, self.tree[r])
r = ll
while left < right:
x = right - right & -right
if left < x:
res = max(res, self.tree[right])
right = x
else:
res = max(res, self.arr[r])
r -= 1
res = max(res, self.arr[right])
right -= 1
return res


Expand Down