Find a pair (n,r) in an integer array such that value of nPr is maximum
Last Updated :
12 Jul, 2025
Given an array of non-negative integers arr[], the task is to find a pair (n, r) such that nPr is the maximum possible and r ≤ n.
nPr = n! / (n - r)!
Examples:
Input: arr[] = {5, 2, 3, 4, 1}
Output: n = 5 and r = 4
5P4 = 5! / (5 - 4)! = 120, which is the maximum possible.
Input: arr[] = {0, 2, 3, 4, 1, 6, 8, 9}
Output: n = 9 and r = 8
Approach: "Brute Force Approach with Sorting"
Naive approach: A simple approach is to consider each (n, r) pair and calculate nPr value and find the maximum value among them.
One possible approach to solve this problem is to sort the given array in decreasing order and then calculate the value of nPr for each possible value of n and r. The first value of nPr that we obtain will be the maximum possible value.
Algorithm:
- Sort the given array arr in decreasing order.
- Initialize max_n to the first element of arr, and max_r to the second element of arr.
- For each possible value of n (starting from max_n), and for each possible value of r (starting from max_r), calculate the value of nPr.
- If the value of nPr is greater than the current maximum, update the values of max_n and max_r.
- Return the values of max_n and max_r.
C++
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
using namespace std;
pair<int, int> find_max_npr(vector<int>& arr) {
sort(arr.begin(), arr.end(), greater<int>());
int max_n = arr[0], max_r = arr[1];
int max_npr = pow(max_n, max_r);
for (int n = max_n; n > 0; --n) {
for (int r = max_r; r > 0; --r) {
int npr = pow(n, r);
if (npr > max_npr) {
max_n = n;
max_r = r;
max_npr = npr;
}
}
}
return make_pair(max_n, max_r);
}
int main() {
vector<int> arr {5, 2, 3, 4, 1};
auto result = find_max_npr(arr);
cout << result.first << " " << result.second << endl; // Output: 5 4
arr = {0, 2, 3, 4, 1, 6, 8, 9};
result = find_max_npr(arr);
cout << result.first << " " << result.second << endl; // Output: 9 8
return 0;
}
Java
import java.util.Arrays;
public class GFG {
public static int[] findMaxNPR(int[] arr) {
// Sort the array in descending order
Arrays.sort(arr);
int maxN = arr[arr.length - 1];
int maxR = arr[arr.length - 2];
int maxNPR = (int) Math.pow(maxN, maxR);
for (int n = maxN; n > 0; n--) {
for (int r = maxR; r > 0; r--) {
int npr = (int) Math.pow(n, r);
if (npr > maxNPR) {
maxN = n;
maxR = r;
maxNPR = npr;
}
}
}
int[] result = {maxN, maxR};
return result;
}
public static void main(String[] args) {
int[] arr1 = {5, 2, 3, 4, 1};
int[] result1 = findMaxNPR(arr1);
System.out.println("Output 1: (" + result1[0] + ", " + result1[1] + ")");
int[] arr2 = {0, 2, 3, 4, 1, 6, 8, 9};
int[] result2 = findMaxNPR(arr2);
System.out.println("Output 2: (" + result2[0] + ", " + result2[1] + ")");
}
}
Python3
def find_max_npr(arr):
arr.sort(reverse=True)
max_n, max_r = arr[0], arr[1]
max_npr = max_n ** max_r
for n in range(max_n, 0, -1):
for r in range(max_r, 0, -1):
npr = n ** r
if npr > max_npr:
max_n, max_r = n, r
max_npr = npr
return max_n, max_r
# Example usage:
arr = [5, 2, 3, 4, 1]
print(find_max_npr(arr)) # Output: (5, 4)
arr = [0, 2, 3, 4, 1, 6, 8, 9]
print(find_max_npr(arr)) # Output: (9, 8)
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
// Function to find the pair (n, r) with the maximum value of n^r
static Tuple<int, int> FindMaxNpr(List<int> arr)
{
// Sort the input array in descending order
arr.Sort((a, b) => b.CompareTo(a));
// Get the maximum values of n and r from the sorted array
int max_n = arr[0];
int max_r = arr[1];
int max_npr = (int)Math.Pow(max_n, max_r);
// Iterate through all possible combinations of n and r
for (int n = max_n; n > 0; n--)
{
for (int r = max_r; r > 0; r--)
{
int npr = (int)Math.Pow(n, r);
// If n^r is greater than the current maximum n^r, update the maximum values
if (npr > max_npr)
{
max_n = n;
max_r = r;
max_npr = npr;
}
}
}
// Return the pair (n, r) with the maximum n^r
return Tuple.Create(max_n, max_r);
}
static void Main()
{
List<int> arr = new List<int> { 5, 2, 3, 4, 1 };
var result = FindMaxNpr(arr);
Console.WriteLine(result.Item1 + " " + result.Item2); // Output: 5 4
arr = new List<int> { 0, 2, 3, 4, 1, 6, 8, 9 };
result = FindMaxNpr(arr);
Console.WriteLine(result.Item1 + " " + result.Item2); // Output: 9 8
}
}
JavaScript
function findMaxNPR(arr) {
arr.sort((a, b) => b - a); // Sort the array in descending order
let max_n = arr[0];
let max_r = arr[1];
let max_npr = Math.pow(max_n, max_r); // Calculate the initial max_npr
for (let n = max_n; n > 0; n--) {
for (let r = max_r; r > 0; r--) {
let npr = Math.pow(n, r); // Calculate n^r
if (npr > max_npr) {
max_n = n;
max_r = r;
max_npr = npr; // Update max_n, max_r, and max_npr if npr is greater
}
}
}
return [max_n, max_r];
}
// Example usage:
let arr = [5, 2, 3, 4, 1];
console.log(findMaxNPR(arr)); // Output: [5, 4]
arr = [0, 2, 3, 4, 1, 6, 8, 9];
console.log(findMaxNPR(arr)); // Output: [9, 8]
Time Complexity: The time complexity of this approach is O(n2), where n is the size of the input array.
Auxiliary Space: The auxiliary space required by this approach is O(1).
Efficient approach: Since nPr = n! / (n - r)! = n * (n - 1) * (n - 2) * ... * (n - r + 1).
With little mathematics, it can be shown that nPr will be maximum when n is maximum and n - r is minimum. The problem now boils down to finding the largest 2 elements from the given array.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <iostream>
using namespace std;
// Function to print the pair (n, r)
// such that nPr is maximum possible
void findPair(int arr[], int n)
{
// There should be atleast 2 elements
if (n < 2) {
cout << "-1";
return;
}
int i, first, second;
first = second = -1;
// Findex the largest 2 elements
for (i = 0; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second) {
second = arr[i];
}
}
cout << "n = " << first
<< " and r = " << second;
}
// Driver code
int main()
{
int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
findPair(arr, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to print the pair (n, r)
// such that nPr is maximum possible
static void findPair(int arr[], int n)
{
// There should be atleast 2 elements
if (n < 2)
{
System.out.print("-1");
return;
}
int i, first, second;
first = second = -1;
// Findex the largest 2 elements
for (i = 0; i < n; i++)
{
if (arr[i] > first)
{
second = first;
first = arr[i];
}
else if (arr[i] > second)
{
second = arr[i];
}
}
System.out.println("n = " + first +
" and r = " + second);
}
// Driver code
public static void main(String args[])
{
int arr[] = { 0, 2, 3, 4, 1, 6, 8, 9 };
int n = arr.length;
findPair(arr, n);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation of the approach
# Function to print the pair (n, r)
# such that nPr is maximum possible
def findPair(arr, n):
# There should be atleast 2 elements
if (n < 2):
print("-1")
return
i = 0
first = -1
second = -1
# Findex the largest 2 elements
for i in range(n):
if (arr[i] > first):
second = first
first = arr[i]
elif (arr[i] > second):
second = arr[i]
print("n =", first, "and r =", second)
# Driver code
arr = [0, 2, 3, 4, 1, 6, 8, 9]
n = len(arr)
findPair(arr, n)
# This code is contributed by mohit kumar
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to print the pair (n, r)
// such that nPr is maximum possible
static void findPair(int[] arr, int n)
{
// There should be atleast 2 elements
if (n < 2)
{
Console.Write("-1");
return;
}
int i, first, second;
first = second = -1;
// Findex the largest 2 elements
for (i = 0; i < n; i++)
{
if (arr[i] > first)
{
second = first;
first = arr[i];
}
else if (arr[i] > second)
{
second = arr[i];
}
}
Console.WriteLine("n = " + first +
" and r = " + second);
}
// Driver code
public static void Main()
{
int[] arr = { 0, 2, 3, 4, 1, 6, 8, 9 };
int n = arr.Length;
findPair(arr, n);
}
}
// This code is contributed by CodeMech
JavaScript
<script>
// Java Script implementation of the approach
// Function to print the pair (n, r)
// such that nPr is maximum possible
function findPair(arr,n)
{
// There should be atleast 2 elements
if (n < 2)
{
document.write("-1");
return;
}
let i, first, second;
first = second = -1;
// Findex the largest 2 elements
for (i = 0; i < n; i++)
{
if (arr[i] > first)
{
second = first;
first = arr[i];
}
else if (arr[i] > second)
{
second = arr[i];
}
}
document.write("n = " + first +
" and r = " + second);
}
// Driver code
let arr = [ 0, 2, 3, 4, 1, 6, 8, 9 ];
let n = arr.length;
findPair(arr, n);
// This code is contributed by sravan kumar
</script>
Time Complexity: O(n)
Auxiliary Space: O(1)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem