LeetCode 题解工作台
将数组分成最小总代价的子数组 I
给你一个长度为 n 的整数数组 nums 。 一个数组的 代价 是它的 第一个 元素。比方说, [1,2,3] 的代价是 1 , [3,4,1] 的代价是 3 。 你需要将 nums 分成 3 个 连续且没有交集 的子数组。 请你返回这些 子数组 的 最小 代价 总和 。 示例 1: 输入: num…
3
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数组·排序
答案摘要
我们记数组 的第一个元素为 ,其余元素中最小的元素为 ,次小的元素为 ,那么答案就是 。 时间复杂度 ,其中 是数组 的长度。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·排序 题型思路
题目描述
给你一个长度为 n 的整数数组 nums 。
一个数组的 代价 是它的 第一个 元素。比方说,[1,2,3] 的代价是 1 ,[3,4,1] 的代价是 3 。
你需要将 nums 分成 3 个 连续且没有交集 的子数组。
请你返回这些子数组的 最小 代价 总和 。
示例 1:
输入:nums = [1,2,3,12] 输出:6 解释:最佳分割成 3 个子数组的方案是:[1] ,[2] 和 [3,12] ,总代价为 1 + 2 + 3 = 6 。 其他得到 3 个子数组的方案是: - [1] ,[2,3] 和 [12] ,总代价是 1 + 2 + 12 = 15 。 - [1,2] ,[3] 和 [12] ,总代价是 1 + 3 + 12 = 16 。
示例 2:
输入:nums = [5,4,3] 输出:12 解释:最佳分割成 3 个子数组的方案是:[5] ,[4] 和 [3] ,总代价为 5 + 4 + 3 = 12 。 12 是所有分割方案里的最小总代价。
示例 3:
输入:nums = [10,3,1,1] 输出:12 解释:最佳分割成 3 个子数组的方案是:[10,3] ,[1] 和 [1] ,总代价为 10 + 1 + 1 = 12 。 12 是所有分割方案里的最小总代价。
提示:
3 <= n <= 501 <= nums[i] <= 50
解题思路
方法一:遍历找最小值和次小值
我们记数组 的第一个元素为 ,其余元素中最小的元素为 ,次小的元素为 ,那么答案就是 。
时间复杂度 ,其中 是数组 的长度。空间复杂度 。
class Solution:
def minimumCost(self, nums: List[int]) -> int:
a, b, c = nums[0], inf, inf
for x in nums[1:]:
if x < b:
c, b = b, x
elif x < c:
c = x
return a + b + c
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
The candidate demonstrates an understanding of sorting-based optimizations for minimizing costs.
- question_mark
The candidate shows proficiency in breaking down the problem into smaller, manageable subproblems.
- question_mark
The candidate efficiently uses enumeration to handle different possible splits of the array.
常见陷阱
外企场景- error
Forgetting to sort the array before attempting to split it into subarrays, which leads to suboptimal cost results.
- error
Not considering all possible splits of the array, leading to missed opportunities for minimizing the total cost.
- error
Overcomplicating the problem by attempting to use advanced data structures instead of sorting and simple array manipulations.
进阶变体
外企场景- arrow_right_alt
Change the number of subarrays to be split into, e.g., 4 or 5 subarrays, adjusting the approach accordingly.
- arrow_right_alt
Consider cases where the cost is defined by a different metric, such as the sum of the elements in the subarray instead of the first element.
- arrow_right_alt
Limit the possible values of elements in the array to a specific range to explore how the problem scales with constraints.