Python 程序用于找出大于给定值的集合的数量
pythonserver side programmingprogramming更新于 2025/5/1 12:28:17
假设我们有一个包含多个整数的数组。我们从给定的数字数组中找出所有连续的子数组并将其放入另一个列表中。现在,我们用该子数组中的最大元素替换每个子数组。还有一个数字 k 给了我们,我们必须找出现在有多少个子数组大于给定的数字。
因此,如果输入为 input_array = [5, 6, 7, 8], k = 7,则输出将为 4
给定输入数组的连续子数组为:{5}, {6}, {7}, {8}, {5, 6}, {6, 7}, {7, 8}, {5, 6, 7}, {6, 7, 8}, {5, 6, 7, 8
如果我们用其中的最大元素更新子数组,则子数组将变为 −
{5}, {6}, {7}, {8}, {6}, {7}, {8}, {7}, {8}, {8}。
有 4 个集合的元素大于 7。
为了解决这个问题,我们将遵循以下步骤 −
- count := 0
- consecutive := 0
- 对于 input_array 中的每个 x,执行
- 如果 x > k,则
- consecutive := 0
- 否则,
- consecutive := consecutive + 1
- count := count + consecutive
- 如果 x > k,则
返回 input_array 的大小 * ((input_array 的大小 + 1) / 2) - count 的下限值
示例
让我们看看下面的实现以便更好地理解 −
def solve(input_array, k): count = 0 consecutive = 0 for x in input_array: if x > k: consecutive = 0 else: consecutive += 1 count += consecutive return len(input_array) * (len(input_array) + 1) // 2 - count print(solve([5, 6, 7, 8], 7))
输入
[5, 6, 7, 8], 7
输出
4
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

