5709 最大升序子数组和
思路:
从队首开始向后遍历,计算当前遍历过的元素和,若当前元素小于其之前的元素,则元素和清零,从该元素开始重新计算。
Python
:
res = [nums[0]]
lens = len(nums)
if lens == 1:
return sum(res)
for i in range(1,lens):
if nums[i] > nums[i-1]:
res.append(res.pop()+nums[i])
else:
res.append(nums[i])
return max(res)
5710 积压订单中的订单总数
思路:
优先队列(堆),购买时需要按照大顶堆进行存放,出售时需要按照小顶堆进行存放。大顶堆每次返回具有最大关键字的元素,小顶堆反之。
代码思想来自于评论区大佬。
Python
:
import heapq
class Solution:
def getNumberOfBacklogOrders(self, orders: List[List[int]]) -> int:
base = 1000000007
res = 0
buy = []
sell = []
for i in orders:
if i[2] == 0:
# python中heapq默认小顶堆存放,因此通过存入相反数实现大顶堆
heapq.heappush(buy, [-i[0],i[1]])
else:
heapq.heappush(sell, [i[0],i[1]])
res += i[1]
while buy:
if not sell or -buy[0][0] < sell[0][0]:
break
x = heapq.heappop(buy)
y = heapq.heappop(sell)
num = min(x[1],y[1])
x[1] -= num
y[1] -= num
res -= 2 * num
if x[1]>0:
heapq.heappush(buy, x)
elif y[1]>0:
heapq.heappush(sell, y)
return res%base
5711 有界数组中指定下标处的最大值
思路:
模拟数组的构建过程,题目在时间上卡的较为严格,需要尽可能优化。
Python
:
class Solution(object):
def maxValue(self, n, index, maxSum):
l = r = index
res = 1
rest = maxSum - n
# 当 l = 0 并且 r = n-1 时,说明整个数组已经拓展完成,若还有剩余,则只需每个元素均 +1
while l > 0 or r < n-1:
lens = r - l + 1
if rest >= lens:
res += 1
rest -= lens
else:
break
l = max(0, l-1)
r = min(n-1, r+1)
res += rest//n
return res
Summary
:
- 题目顺序大部分情况下由易到难,但仍旧尽量所有题目先阅读一遍,比如本次比赛中,如果没有学习堆,第二题将面临超时的问题,反而第三题在没有使用二分的情况下仍旧可以AC。
- 需要学习逆向思维,比如大顶堆的取负构造方式,先加后减的记录方法。