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)
相关推荐
伟大的车尔尼16 小时前
滑动窗口题目:删除子数组的最大得分
滑动窗口
递归尽头是星辰2 天前
双指针与滑动窗口算法精讲:从原理到高频面试题实战
算法·双指针·滑动窗口·子串/子数组问题
ゞ 正在缓冲99%…4 天前
leetcode438.找到字符串中所有字母异位词
leetcode·滑动窗口
3Cloudream6 天前
LeetCode 003. 无重复字符的最长子串 - 滑动窗口与哈希表详解
算法·leetcode·字符串·双指针·滑动窗口·哈希表·中等
HUIMU_11 天前
DAY20-新世纪DL(DeepLearning/深度学习)战士:终(目标检测/YOLO)3
深度学习·yolo·目标检测·滑动窗口·非极大值抑制·交并比·bouding box
蜡笔小柯南12 天前
每秒扛住10万请求?RedissonRateLimiter 分布式限流器详解
分布式·redisson·滑动窗口·ratelimiter
Dream it possible!15 天前
LeetCode 面试经典 150_滑动窗口_串联所有单词的子串(32_30_C++_困难)(滑动窗口:控制起点和滑动距离)
c++·leetcode·面试·滑动窗口
Q741_14720 天前
C++ 力扣 76.最小覆盖子串 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口
Q741_1471 个月前
C++ 力扣 438.找到字符串中所有字母异位词 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口
Tisfy1 个月前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率