本文最后更新于 3 分钟前,文中所描述的信息可能已发生改变。
3652. 按策略买卖股票的最佳时机 - 力扣(LeetCode)
题目类型
#前缀和 #滑动窗口
解题思路
前缀和模拟即可,注意区间边界
示例代码
python
class Solution:
def maxProfit(self, prices: List[int], strategy: List[int], k: int) -> int:
n = len(prices)
pre = list(accumulate(prices, initial=0))
cost = [0] * (n + 1)
for i, (p, s) in enumerate(zip(prices, strategy)):
cost[i + 1] = cost[i] + p * s
ans = cost[-1]
for i in range(n - k + 1):
tmp = cost[-1] - (cost[i + k] - cost[i]) + pre[i + k] - pre[i + k // 2]
ans = max(ans, tmp)
return ans3653. 区间乘法查询后的异或 I - 力扣(LeetCode)
题目类型
#模拟
解题思路
暴力模拟即可
示例代码
python
class Solution:
def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int:
mod = 10 ** 9 + 7
for l, r, k, v in queries:
for i in range(l, r + 1, k):
nums[i] *= v
nums[i] %= mod
return reduce(xor, nums)3654. 删除可整除和后的最小数组和 - 力扣(LeetCode)
题目类型
#动态规划 #前缀和
解题思路
取整为 0 意味着余数相同,取余数相同的相邻区间不断更新答案。可以考虑取最大值或取最小值
示例代码
python
fmax = lambda x, y: x if x > y else y
class Solution:
def minArraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
pre = list(accumulate(nums, initial=0))
d = {}
f = [0] * (n + 2)
for i, x in enumerate(pre):
f[i + 1] = f[i]
if x % k in d:
j = d[x % k]
f[i + 1] = fmax(f[i + 1], f[j + 1] + x - pre[j])
d[x % k] = i
return pre[-1] - f[-1]python
fmin = lambda x, y: x if x < y else y
class Solution:
def minArraySum(self, nums: List[int], k: int) -> int:
n = len(nums)
f = [inf] * k
f[0] = 0
ans = s = 0
for x in nums:
s = (s + x) % k
ans = fmin(f[s], ans + x)
f[s] = ans
return ans3655. 区间乘法查询后的异或 II - 力扣(LeetCode)
题目类型
#差分数组 #商分数组 #根号分治 #逆元
解题思路
示例代码
python
class Solution:
def xorAfterQueries(self, nums: List[int], queries: List[List[int]]) -> int:
MOD = 10 ** 9 + 7
n = len(nums)
B = isqrt(len(queries))
diff = [None] * B
for l, r, k, v in queries:
if k < B:
if not diff[k]:
diff[k] = [1] * (n + k)
diff[k][l] = diff[k][l] * v % MOD
r = r + k - (r - l) % k
diff[k][r] = diff[k][r] * pow(v, -1, MOD) % MOD
else:
for i in range(l, r + 1, k):
nums[i] = nums[i] * v % MOD
for k, d in enumerate(diff):
if not d:
continue
for st in range(k):
m = 1
for i in range(st, n, k):
m = m * d[i] % MOD
nums[i] = nums[i] * m % MOD
return reduce(xor, nums)