Competitive ProgrammingMedium

Lexicographically largest array

Detailed guide and Python implementation for the 'Lexicographically largest array' problem.

Problem Statement

Medium

Write a function lexicographically_largest(arr, k) that returns the lexicographically largest array that can be obtained by swapping adjacent elements at most k times. Elements in arr are unique.

Constraints
  • 1 <= len(arr) <= 1000
  • 0 <= k <= 10^5
  • -10^9 <= arr[i] <= 10^9

Examples

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?
Consider using Greedy-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.