-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem.py
More file actions
32 lines (26 loc) · 821 Bytes
/
Copy pathproblem.py
File metadata and controls
32 lines (26 loc) · 821 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from heapq import heappop, heappush
from typing import List
from struct.sparse_table.template import SparseTable
class Solution:
def lc3691(self, nums: List[int], k: int) -> int:
"""
link: https://leetcode.cn/problems/maximum-total-subarray-value-ii/
"""
n = len(nums)
h = []
mxt = SparseTable(nums, max)
mnt = SparseTable(nums, min)
def query(l: int, r: int) -> int:
return mxt.query(l, r) - mnt.query(l, r)
for i in range(n):
heappush(h, (-query(i, n - 1), i, n - 1))
ans = 0
while k:
k -= 1
x, l, r = heappop(h)
ans -= x
if l == r:
continue
s = query(l, r - 1)
heappush(h, (-s, l, r - 1))
return ans