702865. Largest Permutation

Easy

Largest Permutation

Slug: largest-permutation1351

Difficulty: Easy

Id: 702865

Topic Tags: Arrays, Greedy, Data Structures, Algorithms

Company Tags: None

Summary

Given a permutation of size n, the task is to find the largest possible permutation. A permutation is an arrangement of all integers from 1 to n in some order.

Detailed Explanation

To solve this problem, we can use a greedy approach. We initialize our result with the maximum value (n) and then iterate over the range [n-1, 1]. For each iteration, we add the current value to our result if it's greater than or equal to the last element in our result. This ensures that our result is always increasing.

Here's a step-by-step breakdown of the solution:

  • Initialize an empty list result and set its first element to n.
  • Iterate over the range [n-1, 1] (inclusive).
  • For each iteration, check if the current value is greater than or equal to the last element in result. If it is, add it to result.
  • Return the result.

The time complexity of this solution is O(n), where n is the size of the permutation. The space complexity is also O(n) as we need to store the result.

Here's an ASCII art diagram illustrating the approach:

  n (max value)
  v
1, 2, ..., n-1 (range)

iterate over range:
  n-1: add if > last element in result
  n-2: add if > last element in result
  ...
  1: add if > last element in result

result = [n, n-1, ..., 2, 1]

Optimized Solutions

Java

View on GeeksforGeeks
public static int[] largestPermutation(int n) {
    int[] result = new int[n];
    for (int i = n - 1; i >= 0; i--) {
        if (i < result[i]) {
            result[i] = i + 1;
        }
    }
    return result;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.