주어진 작업이 0에서 9까지의 모든 한 자리 숫자에 대한 대안으로 10자리를 포함하는 다른 배열을 사용하여 해당 자리를 대체하여 주어진 숫자를 'N'자리로 최대화하는 것인 경우
주어진 조건은 숫자의 연속적인 부분만 교체할 수 있고 한 번만 대체할 수 있다는 것입니다.
입력
N=1234, arr[]={3 ,0 ,1 ,5 ,7 ,7 ,8 ,2 ,9 ,4} 출력
1257
설명
숫자 3은 대체 5=arr[3]
로 대체될 수 있습니다.숫자 4는 대체 7=arr[4]
로 대체될 수 있습니다.입력
N=5183, arr[]={3 ,0 ,1 ,5 ,7 ,7 ,8 ,2 ,9 ,4} 출력
7183
아래 프로그램에서 사용하는 접근 방식은 다음과 같습니다.
-
Max() 함수에서 숫자의 크기를 저장하기 위해 int 유형의 변수 'N'을 만듭니다.
-
i=0에서 i
-
그런 다음 번호를 다른 번호로 바꾸십시오.
-
더 작은 대안이 있는 번호를 찾을 수 없을 때까지 다음 번호에 대해 이 작업을 수행합니다.
예시
#include <bits/stdc++.h>
using namespace std;
string Max(string str, int arr[]){
int N = str.size();
//Iterating till the end of string
for (int i = 0; i < N; i++) {
//Checking if it is greater or not
if (str[i] - '0' < arr[str[i] - '0']) {
int j = i;
//Replacing with the alternate till smaller
while (j < N && (str[j] - '0' <= arr[str[j] - '0'])) {
str[j] = '0' + arr[str[j] - '0'];
j++;
}
return str;
}
}
// Returning original str if there is no change
return str;
}
//Main function
int main(){
string str = "2075";
int arr[] = {3 ,0 ,1 ,5 ,7 ,7 ,8 ,2 ,9 ,4 };
cout <<” Maximize the given number by replacing a segment of digits with the alternate digits given is: ” <<Max(str, arr);
return 0;
} 출력
위의 코드를 실행하면 다음과 같은 결과가 나옵니다. -
Maximize the given number by replacing a segment of digits with the alternate digits given is: 2375