Maximize a number considering permutations with values smaller than limit
Last Updated :
02 Aug, 2022
Given two numbers N and M. Construct maximal number by permuting (changing order) the digits of N, not exceeding M.
Note: It is allowed to leave N as it is.
Examples:
Input : N = 123, M = 222
Output : 213
There are total 3! permutations possible for N = 123, But the only permutation that satisfies the given condition is 213. Similarly, In example 2, there are total 4! permutations possible for N = 3921, But the only permutation that satisfies the given condition is 9321.
Input : N = 3921, M = 10000
Output : 9321
Approach: Let's construct the answer digit by digit starting from the leftmost. We are asked to build a lexicographically maximal answer. So in this order, we should choose the greatest digit on each step. The approach is to iterate over all possible digits starting from the greatest. For each digit check if it's possible to put it in this position and compare the resulting number with the number M. If it comes less than or equal to the value of M, then proceed to the next digit.
Below is the CPP implementation of the above approach:
CPP
// CPP program to Maximize the given number.
#include <bits/stdc++.h>
using namespace std;
// Function to maximize the number N with
// limit as M.
string maximizeNumber(string N, int M)
{
// Sorting the digits of the
// number in increasing order.
sort(N.begin(), N.end());
for (int i = 0; i < N.size(); i++) {
for (int j = i + 1; j < N.size(); j++) {
// Copying the string into another
// temp string.
string t = N;
// Swapping the j-th char(digit)
// with i-th char(digit)
swap(t[j], t[i]);
// Sorting the temp string
// from i-th pos to end.
sort(t.begin() + i + 1, t.end());
// Checking if the string t is
// greater than string N and less
// than or equal to the number M.
if (stoll(t) > stoll(N) && stoll(t) <= M)
// If yes then, we will permanently
// swap the i-th char(or digit)
// with j-th char(digit).
swap(N[i], N[j]);
}
}
// Returns the maximized number.
return N;
}
// Driver function
int main()
{
string N = "123";
int M = 222;
cout << maximizeNumber(N, M);
return 0;
}
// This code is contributed by KaaL-EL.
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.Arrays;
class GFG {
// Java has no built-in swap function.
public static String swap(String str, int i, int j)
{
char ch[] = str.toCharArray();
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return new String(ch);
}
// Since STRINGS are immutable in Java, first we have to
// convert it to a character array in order to sort.
public static String
sortString(String string, int s_index, int e_index)
{
char tempArray[] = string.toCharArray();
// Sorting temp array using
Arrays.sort(tempArray, s_index, e_index);
// returning the new sorted string
return new String(tempArray);
}
public static String maximizeNumber(String N, int M)
{
// Sorting the digits of the
// number in increasing order.
N = sortString(N, 0, N.length());
for (int i = 0; i < N.length(); i++) {
for (int j = i + 1; j < N.length(); j++) {
// Copying the string into another
// temp string.
String t = N;
// Swapping the j-th char(digit)
// with i-th char(digit)
t = swap(t, j, i);
// Sorting the temp string
// from i-th pos to end.
t = sortString(t, i + 1, t.length());
// Checking if the string t is
// greater than string N and less
// than or equal to the number M.
if (Long.parseLong(t) > Long.parseLong(N)
&& Long.parseLong(t) <= M)
// If yes then, we will permanently
// swap the i-th char(or digit)
// with j-th char(digit).
N = swap(N, i, j);
}
}
// Returns the maximized number.
return N;
}
// Driver Code
public static void main(String[] args)
{
String N = "123";
int M = 222;
System.out.println(maximizeNumber(N, M));
}
}
//This code is contributed by KaaL-EL.
Python3
# Python3 program to implement the approach
# Python3 has no built-in swap function.
def swap(str, i, j):
ch = list(str)
temp = ch[i]
ch[i] = ch[j]
ch[j] = temp
return "".join(ch)
# Since STRINGS are immutable in JavaScript, first we have
# to convert it to a character array in order to sort.
def sortString(str, s_index, e_index):
tempArray = list(str)
# Sorting temp array using
tempArray = tempArray[:s_index] + sorted(tempArray[s_index: e_index])
# returning the new sorted string
return "".join(tempArray)
def maximizeNumber(N, M):
# Sorting the digits of the
# number in increasing order.
N = sortString(N, 0, len(N))
for i in range(len(N)):
for j in range(i + 1, len(N)):
# Copying the string into another
# temp string.
t = N
# Swapping the j-th char(digit)
# with i-th char(digit)
t = swap(t, j, i)
# Sorting the temp string
# from i-th pos to end.
t = sortString(t, i + 1, len(t))
# Checking if the string t is
# greater than string N and less
# than or equal to the number M.
if (int(t) > int(N) and int(t) <= M):
# If yes then, we will permanently
# swap the i-th char(or digit)
# with j-th char(digit).
N = swap(N, i, j)
# Returns the maximized number.
return N
# Driver Code
N = "123"
M = 222
print(maximizeNumber(N, M))
# This code is contributed by phasing17
C#
// C# program to implement the approach
using System;
using System.Collections.Generic;
class GFG {
// C# has no built-in swap function.
public static string swap(String str, int i, int j)
{
char[] ch = str.ToCharArray();
char temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return new string(ch);
}
// Since STRINGS are immutable in C#, first we have to
// convert it to a character array in order to sort.
public static string sortString(string str, int s_index,
int e_index)
{
char[] tempArray = str.ToCharArray();
// Sorting temp array using
Array.Sort(tempArray, s_index, e_index - s_index);
// returning the new sorted string
return new string(tempArray);
}
public static string maximizeNumber(string N, int M)
{
// Sorting the digits of the
// number in increasing order.
N = sortString(N, 0, N.Length);
for (int i = 0; i < N.Length; i++) {
for (int j = i + 1; j < N.Length; j++) {
// Copying the string into another
// temp string.
string t = N;
// Swapping the j-th char(digit)
// with i-th char(digit)
t = swap(t, j, i);
// Sorting the temp string
// from i-th pos to end.
t = sortString(t, i + 1, t.Length);
// Checking if the string t is
// greater than string N and less
// than or equal to the number M.
if (Convert.ToInt64(t) > Convert.ToInt64(N)
&& Convert.ToInt64(t) <= M)
// If yes then, we will permanently
// swap the i-th char(or digit)
// with j-th char(digit).
N = swap(N, i, j);
}
}
// Returns the maximized number.
return N;
}
// Driver Code
public static void Main(string[] args)
{
string N = "123";
int M = 222;
Console.WriteLine(maximizeNumber(N, M));
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript program to implement the approach
// JavaScript has no built-in swap function.
function swap(str, i, j)
{
let ch = str.split("");
let temp = ch[i];
ch[i] = ch[j];
ch[j] = temp;
return ch.join("");
}
// Since STRINGS are immutable in JavaScript, first we have
// to convert it to a character array in order to sort.
function sortString(str, s_index, e_index)
{
let tempArray = str.split("");
// Sorting temp array using
tempArray
= tempArray.slice(0, s_index)
.concat(
tempArray.slice(s_index, e_index).sort());
// returning the new sorted string
return tempArray.join("");
}
function maximizeNumber(N, M)
{
// Sorting the digits of the
// number in increasing order.
N = sortString(N, 0, N.length);
for (var i = 0; i < N.length; i++) {
for (var j = i + 1; j < N.length; j++) {
// Copying the string into another
// temp string.
let t = N;
// Swapping the j-th char(digit)
// with i-th char(digit)
t = swap(t, j, i);
// Sorting the temp string
// from i-th pos to end.
t = sortString(t, i + 1, t.length);
// Checking if the string t is
// greater than string N and less
// than or equal to the number M.
if (parseInt(t) > parseInt(N)
&& parseInt(t) <= M)
// If yes then, we will permanently
// swap the i-th char(or digit)
// with j-th char(digit).
N = swap(N, i, j);
}
}
// Returns the maximized number.
return N;
}
// Driver Code
let N = "123";
let M = 222;
console.log(maximizeNumber(N, M));
// This code is contributed by phasing17
Time complexity : O(n3 log n)
Auxiliary Space: O(n), since n extra space has been taken.
Similar Reads
Maximize the number of local maxima's with minimum operations Given an array A[] of size N (where N is even), Local maxima are array elements strictly greater in value than its adjacent elements i.e., A[i - 1] < A[i] > A[i + 1]. For all 2 ⤠i ⤠N - 1. The first and last element of the array can never be Local maxima. The task is to maximize the number of
15+ min read
Find the Number of Permutations that satisfy the given condition in an array Given an array arr[] of size N, the task is to find the number of permutations in the array that follows the given condition: If K is the maximum element in the array, then the elements before K in the array should be in the ascending order and the elements after K in the array should be in the desc
12 min read
Maximum value with the choice of either dividing or considering as it is We are given a number n, we need to find the maximum sum possible with the help of following function: F(n) = max( (F(n/2) + F(n/3) + F(n/4) + F(n/5)), n). To calculate F(n, ) we may either have n as our result or we can further break n into four part as in given function definition. This can be don
5 min read
Find permutation with maximum remainder Sum Given an integer N, the task is to find a permutation of the integers from 1 to N such that \sum_{i=1}^{N}P_i\mod i is maximum. Examples: Input: N = 3 Output: 3 1 2 Sum of the remainder values is (0 + 1 + 2) = 3 which is the maximum possible.Input: N = 5 Output: 5 1 2 3 4 Approach: As it is known th
4 min read
Maximum sum subsequence with values differing by at least 2 Given a positive integer array arr[] of size N, the task is to find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent to the value i.e. if arr[i] is taken into the answer, then neither occurrences of arr[i]-1 nor arr[i]+1 can be selected. Examp
10 min read