競賽程式設計中等

按字典順序最大的數組

“字典最大數組”問題的詳細指南和 Python 實作。

問題陳述

中等

寫一個函數 lexicographically_largest(arr, k) ,傳回依字典順序排列的最大數組,該數組可以透過最多交換相鄰元素 k 次來獲得。 arr 中的元素是唯一的。

約束條件
  • 1 <= len(arr) <= 1000
  • 0 <= k <= 10^5
  • -10^9 <= arr[i] <= 10^9

範例

Example 1
Input
lexicographically_largest([1, 2, 3, 4, 5], 3)
Output
[4, 1, 2, 3, 5]
Explanation

To get the largest possible element 4 as close to the front as possible, we swap it forward, requiring 3 swaps: [1, 2, 3, 4, 5] -> [1, 2, 4, 3, 5] -> [1, 4, 2, 3, 5] -> [4, 1, 2, 3, 5].

Example 2
Input
lexicographically_largest([3, 5, 4, 1, 2], 1)
Output
[5, 3, 4, 1, 2]
Explanation

Swap 3 and 5 (1 swap) to get [5, 3, 4, 1, 2].

Need a Hint?
考慮使用特定於貪婪的資料結構,例如集合或堆疊。
Edge Cases to Watch
  • 空輸入結構
  • 單元素輸入
  • 大數值範圍

準備好解決了嗎?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

在編輯器中開啟
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推薦的 Python 資源

透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。