Open In App
Related Articles

Find a pair (n,r) in an integer array such that value of nPr is maximum

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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]

                    

Output
(5, 4)
(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>

                    

Output
n = 9 and r = 8





Time Complexity: O(n)
Auxiliary Space: O(1)



Last Updated : 29 Aug, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads