在 C++ 中透過用 B 中的一些數字替換 A 的一些數字來最大化 A 的值


任務是透過替換數字 A 中的一些數字為另一個數字 B 中存在的數字來最大化數字 A 的值。如果無法最大化 A 的值,則不會替換任何數字。

注意 - B 中的數字只能使用一次。

現在讓我們用一個例子來理解我們必須做什麼 -

輸入 

A = “1221”
B = “1211”

輸出 

Maximum value of A possible 2221

解釋 - 我們在這裡從 B 中選擇 2 並用它替換 A 的第一個 1。這是唯一的選擇,因為用 2 或 1 替換 A 的任何其他數字都不會增加它的值。

輸入 

A = “1002”
B = “3200”

輸出 

Maximum value of A possible 3202

下面程式中使用的途徑如下

  • 如果 A 中的每個數字都小於 B 中的數字,則將 A 中的每個數字替換為 B 中的一個數字。

  • 按升序對字串 B 進行排序。

  • 從左開始遍歷 A。

  • 現在從右開始遍歷 B。

  • 如果 A 中的數字小於 B 中的數字,則將 A 中的數字替換為 B 中的數字,並將 A 的指標加 1,B 的指標減 1。

示例

 即時演示

#include <bits/stdc++.h>
using namespace std;
// Function to return the maximized value of a
string valueup(string str1, string str2){
   // Sort digits in ascending order
   sort(str2.begin(), str2.end());
   int len1 = str1.length();
   int len2 = str2.length();
   int j = len2 - 1;
   for (int i = 0; i < len1; i++) {
      // If all the digits of b consumed
      if (j < 0)
         break;
      if (str2[j] > str1[i]) {
         str1[i] = str2[j];
         j--; //once digit used
      }
   }
   return str1;
}
// Driver code
int main(){
   string a = "1204";
   string b = "4521";
   cout << valueup(a, b);
   return 0;
}

輸出

如果我們執行以上程式碼,我們將得到以下輸出 -

5424

更新於: 2020-08-14

115 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告