当前位置:网站首页>LeetCode simple problem to find the subsequence of length K with the largest sum
LeetCode simple problem to find the subsequence of length K with the largest sum
2022-07-31 03:04:00 【·The sea of stars】
题目
给你一个整数数组 nums 和一个整数 k .你需要找到 nums 中长度为 k 的 子序列 ,且这个子序列的 和最大 .
请你返回 任意 一个长度为 k 的整数子序列.
子序列 定义为从一个数组里删除一些元素后,不改变剩下元素的顺序得到的数组.
示例 1:
输入:nums = [2,1,3,3], k = 2
输出:[3,3]
解释:
子序列有最大和:3 + 3 = 6 .
示例 2:
输入:nums = [-1,-2,3,4], k = 3
输出:[-1,3,4]
解释:
子序列有最大和:-1 + 3 + 4 = 6 .
示例 3:
输入:nums = [3,4,3,3], k = 2
输出:[3,4]
解释:
子序列有最大和:3 + 4 = 7 .
另一个可行的子序列为 [4, 3] .
提示:
1 <= nums.length <= 1000
-10^5 <= nums[i] <= 10 ^5
1 <= k <= nums.length
来源:力扣(LeetCode)
解题思路
The result array required by this question does not need to be contiguous in the original array,This greatly reduces the difficulty of the problem,So the first step is to sort the given array first,Then take the largest elements and their subscripts,Then intercept the results that meet the conditions and return the correct sequence in the original array.
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
new_nums=sorted(enumerate(nums),key=lambda x:-x[1])
ans=sorted(new_nums[0:k],key=lambda x:x[0])
return [i[1] for i in ans]

Of course, this question does not need to be completely sorted,The best way to do this is to use selection sort to match the conditionskAfter one is selected, it will not continue to sort.
class Solution:
def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
ans=[]
for i in range(k):
MAX,index=-float('inf'),-1
for j in enumerate(nums):
if j[1]!=None:
if j[1]>MAX:
MAX,index=j[1],j[0]
ans.append((index,MAX))
nums[index]=None
return [i[1] for i in sorted(ans)]

边栏推荐
猜你喜欢

字体压缩神器font-spider的使用

LeetCode简单题之找到和最大的长度为 K 的子序列

7. List of private messages

Mysql 45讲学习笔记(二十四)MYSQL主从一致

【Android】Room —— SQLite的替代品

php 网站的多语言设置(IP地址区分国内国外)

YOLOV5 study notes (2) - environment installation + operation + training

Chapter 9 SVM Practice

SQL注入 Less46(order by后的注入+rand()布尔盲注)

10 Permission introduction
随机推荐
CorelDRAW2022精简亚太新增功能详细介绍
Chapter 9 SVM Practice
The simulation application of common mode inductance is here, full of dry goods for everyone
JS 函数 this上下文 运行时点语法 圆括号 数组 IIFE 定时器 延时器 self.备份上下文 call apply
7年经验,功能测试工程师该如何一步步提升自己的能力呢?
StringJoiner in detail
MultipartFile file upload
Local area network computer hardware information collection tool
JS function this context runtime syntax parentheses array IIFE timer delay self.backup context call apply
SQL injection Less46 (injection after order by + rand() Boolean blind injection)
你们程序员为什么不靠自己的项目谋生?而必须为其他人打工?
7、私信列表
跨专业考研难度大?“上岸”成功率低?这份实用攻略请收下!
Project (5) - Small target detection tph-yolov5
C primer plus学习笔记 —— 8、结构体
学习DAVID数据库(1)
15. Website Statistics
2022牛客多校联赛第四场 题解
刚出道“一战成名”,安全、舒适一个不落
YOLOV5学习笔记(二)——环境安装+运行+训练