LeetCode 题解工作台

最多 K 个元素的子序列的最值之和

给你一个整数数组 nums 和一个正整数 k ,返回所有长度最多为 k 的 子序列 中 最大值 与 最小值 之和的总和。 非空子序列 是指从另一个数组中删除一些或不删除任何元素(且不改变剩余元素的顺序)得到的数组。 由于答案可能非常大,请返回对 10 9 + 7 取余数的结果。 示例 1: 输入: …

category

5

题型

code_blocks

0

代码语言

hub

3

相关题

当前训练重点

中等 · 状态·转移·动态规划

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 状态·转移·动态规划 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个整数数组 nums 和一个正整数 k,返回所有长度最多为 k子序列 中 最大值 与 最小值 之和的总和。

非空子序列 是指从另一个数组中删除一些或不删除任何元素(且不改变剩余元素的顺序)得到的数组。

由于答案可能非常大,请返回对 109 + 7 取余数的结果。

 

示例 1:

输入: nums = [1,2,3], k = 2

输出: 24

解释:

数组 nums 中所有长度最多为 2 的子序列如下:

子序列 最小值 最大值
[1] 1 1 2
[2] 2 2 4
[3] 3 3 6
[1, 2] 1 2 3
[1, 3] 1 3 4
[2, 3] 2 3 5
总和     24

因此,输出为 24。

示例 2:

输入: nums = [5,0,6], k = 1

输出: 22

解释:

对于长度恰好为 1 的子序列,最小值和最大值均为元素本身。因此,总和为 5 + 5 + 0 + 0 + 6 + 6 = 22

示例 3:

输入: nums = [1,1,1], k = 2

输出: 12

解释:

子序列 [1, 1][1] 各出现 3 次。对于所有这些子序列,最小值和最大值均为 1。因此,总和为 12。

 

提示:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
  • 1 <= k <= min(100, nums.length)
lightbulb

解题思路

方法一

1
2

speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    The candidate demonstrates understanding of dynamic programming and state transitions.

  • question_mark

    The candidate suggests sorting the array as a means to simplify subsequence generation.

  • question_mark

    The candidate efficiently handles the modulo operation to ensure correct results for large sums.

warning

常见陷阱

外企场景
  • error

    Forgetting to apply the modulo operation may lead to incorrect results.

  • error

    Not sorting the array, which leads to inefficient subsequence calculations.

  • error

    Overlooking edge cases, such as when k equals 1 or when nums contains duplicate values.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Adjusting the value of k to examine subsequences of varying sizes.

  • arrow_right_alt

    Changing the problem to find only the maximum or minimum sums.

  • arrow_right_alt

    Modifying the problem to return only the sum for a specific subsequence size.

help

常见问题

外企场景

最多 K 个元素的子序列的最值之和题解:状态·转移·动态规划 | LeetCode #3428 中等