找到可词典的最小序列

问题描述

这是问题陈述

Given a sequence of n integers arr,determine the lexicographically smallest sequence which may be obtained from it after performing at most k element swaps,each involving a pair of consecutive elements in the sequence.
Note: A list x is lexicographically smaller than a different equal-length list y if and only if,for the earliest index at which the two lists differ,x's element at that index is smaller than y's element at that index.

基于以上说明,我试图绕过“按字典顺序较小”一词的含义。据我了解它的英文含义,我们基本上是在谈论字典顺序。让我用一个例子来解释我的问题。

这里有个例子

Example 1
n = 3
k = 2
arr = [5,3,1]
output = [1,5,3]
We can swap the 2nd and 3rd elements,followed by the 1st and 2nd elements,to end up with the sequence [1,3]. This is the lexicographically smallest sequence achievable after at most 2 swaps.

上面的示例附带问题说明。但是,按词典顺序排列的最小序列不是[1,3,5]而是提供的答案(输出)[1,4,3]吗?

这是另一个

Example 2
n = 5
k = 3
arr = [8,9,11,2,1]
output = [2,8,1]
We can swap [11,2],followed by [9,then [8,2].

同样,在这种情况下,我可以看到的答案是[1、2、8、11、9](经过三次交换),这是最小的词典盟友,输出的答案为[2、8、9] ,11,1]。

错误地阅读了问题说明吗?

解决方法

问题陈述说,我们被允许在过程中最多进行k个连续元素的交换,以获得字典上最小的序列。以下说明可以帮助我们更好地理解它。 [注意:请记住,您只能交换连续的元素]

  1. n = 3
    k = 2
    arr = [5,3,1]
    输出= [1、5、3]
    方法
    交换1:交换3和1(3 1)====> [5,1,3]
    交换2:交换5和1(5 1)====> [1,5,3] #RESULT
  2. n = 5
    k = 3
    arr = [8、9、11、2、1]
    输出= [2、8、9、11、1]
    方法
    交换1:交换11和2(11 2)===> [8、9、2、11、1]
    交换2:交换9和2(9 2)===> [8、2、9、11、1]
    交换2:交换8和2(9 2)===> [2,8,9,9,11,1] #RESULT

因此,通过连续元素的3次交换,您将永远无法获得[1、2、8、11、9]。 2是您可以移动到第一个索引的最小元素,最多可以连续交换3个元素,但是是的,如果k = 4,那么我们可以将1移到第一个位置。

因此,您所缺少的是该规则允许您最多交换k个元素,但是交换的元素应该彼此连续。