Find a pair (n,r) in an integer array such that value of nPr is maximum
Last Updated :
29 Aug, 2023
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
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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