You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.
Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.
A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
題目給我們一串數列nums,咱需要把它拆解成至少一個子序列,而且每個元素只會存在在一個子序列中!
目標是返回所需的最小子序列數量,使得每個子序列中的最大值和最小值之間的差不超過k。
題目還定義了子序列:可以從一個序列中透過刪除一些元素(或不刪除任何元素)而產生的新序列,並且保持剩下的元素的順序不變。
我的解題思路:
class Solution {
public int partitionArray(int[] nums, int k) {
// 排序
Arrays.sort(nums);
int count = 1; // 至少有一個子序列
int start = nums[0];
// 遍歷
for (int i = 1 ; i < nums.length ; i++) {
// 最大、最小差值大於k,就開一個新的子序列
if (nums[i] - start > k) {
count++;
start = nums[i]; // 更新新的子序列的開頭
}
}
return count;
}
}
今天的題目偏簡單,雖然我一開始有困惑一下,因為記憶中的子序列定義應該是連續元素!
重讀題目幾次後才發現貓膩,原來解題關鍵就在這裡!我把它想的太複雜了!!