OD C卷 - 最多购买宝石数目

最多购买宝石数目(100)

  • 输入宝石数量n,随后n行输入每个宝石的价格;
  • 宝石可以同时出售0或者多个,多个时,宝石编号必须连续;
  • 对当前总面值v的钱,最多能购买多少个宝石,如无法购买返回0;

示例1

输入

7

8

4

6

3

1

6

7

10

输出

3

说明:

最多购买的宝石索引为2->4 或者3->5

示例2

输入

0

1

输出

0

示例3

输入

9

6

1

3

1

8

9

3

2

4

15

输出

4

示例4

输入

9

1

1

1

1

1

1

1

1

1

10

输出

9

思路:

  • 滑动窗口,从最大长度为n,依次递减,直到满足要求(连续和<= v);
python 复制代码
# 宝石总数
n = int(input().strip())

# 每个宝石的价格
price = []
for i in range(n):
    price.append(int(input().strip()))

# 总钱数
v = int(input().strip())

# 长度 从最大开始
length = n
label = False
while length > 0:
    for i in range(n - length + 1):
        temp = price[i:i+length]  # 分片效率低
        if sum(temp) <= v:
            label = True
    if label:
        break
    length -= 1

print(length)
 
  • 双指针+滑动窗口
python 复制代码
# 宝石总数
n = int(input().strip())

# 每个宝石的价格
price = []
for i in range(n):
    price.append(int(input().strip()))

# 总钱数
v = int(input().strip())

#
end = 0
start = 0
length = 0
total_used = 0
while end < n:
    total_used += price[end]
    while v < total_used:
        total_used -= price[start]
        start += 1

    length = max(end - start + 1, length)

    end += 1

print(length)
相关推荐
wy_hhxx1 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
ashiho8 天前
【LeetCode hot 100】3. 无重复字符的最长子串 (三种解法)
java·数据结构·后端·算法·leetcode·滑动窗口
拂拉氏13 天前
【知识讲解-题目讲解】 统计满足K约束的子字符串数量2 (滑动窗口+前缀和+二分查找+分析)
算法·前缀和·二分查找·滑动窗口
张彦峰ZYF20 天前
放行、排队与拒绝:限流设计的算法选型、数据结构与并发代价
后端·架构·滑动窗口·漏桶·令牌桶·高并发+限流
yi0111 个月前
LeetCode 424. 替换后的最长重复字符|不定长滑动窗口:如何判断窗口是否合法?
笔记·python·算法·leetcode·双指针·滑动窗口
yi0111 个月前
LeetCode 3. 无重复字符的最长子串|不定长滑动窗口:什么时候更新最大值?
笔记·python·算法·leetcode·双指针·滑动窗口
yi0111 个月前
LeetCode 643. 子数组最大平均数 I|从暴力枚举到滑动窗口
人工智能·笔记·python·算法·leetcode·滑动窗口
longlongzihan2 个月前
LeetCode 76. 最小覆盖子串:滑动窗口算法详解
算法·leetcode·滑动窗口
longlongzihan2 个月前
LeetCode 1004.最大连续1的个数III 滑动窗口及动态规划题解
c++·算法·leetcode·dp·滑动窗口
Logic1012 个月前
C语言/数据结构滑动窗口题解:替换k个字符后的最长连续相同字符子串(LeetCode 424)
c语言·数据结构·字符串·滑动窗口·时间复杂度·频率统计·算法题