通过特定顺序排列数字得到最大数 (C++)
在这个问题中,我们得到一个数字数组,需要找到通过特定方式排列这些数字后能够得到的最大值。排列条件是:偶数和奇数的顺序必须保持不变,即所有偶数的顺序不能改变。
让我们通过一个例子来更好地理解这个概念:
Input : {17, 80, 99, 27, 14 , 22} Output: 801799271422 Explanation: the order of Even and Odd numbers is : Even : 80 14 22 Odd : 17 99 27
这里 99 是最大的数字,但是 17 在奇数序列中排在 99 之前,所以我们先考虑 80,然后按顺序排列,例如:**80 17 99 27 14 22**
既然我们已经理解了这个问题,让我们尝试为其找到解决方案。由于定义了奇偶数序列的约束,我们不能采用经典的降序排列方法。我们需要保持这个序列,并检查奇偶数序列中第一个元素的最大值,然后以此类推。让我们来看一个算法,这会使问题更加清晰。
算法
Step 1 : Create two structures, one for even other for odd, this will maintain the sequence. Step 2 : Take one element from each structure and check which combination makes a large number. Example, if E is the even number and O is the odd number which are at the top of the structure. then we will check which one is Greater of EO and OE. Step 3 : Place the greater combination into the final sequence. Step 4 : Print the final sequence.
示例
现在,让我们根据这个算法创建一个程序。
#include <bits/stdc++.h> using namespace std; string merge(vector<string> arr1, vector<string> arr2) { int n1 = arr1.size(); int n2 = arr2.size(); int i = 0, j = 0; string big = ""; while (i < n1 && j < n2) { if ((arr1[i]+arr2[j]).compare((arr2[j]+arr1[i])) > 0) big += arr1[i++]; else big += arr2[j++]; } while (i < n1) big += arr1[i++]; while (j < n2) big += arr2[j++] ; return big; } string largestNumber(vector<string> arr, int n) { vector<string> even, odd; for (int i=0; i<n; i++) { int lastDigit = arr[i].at(arr[i].size() - 1) - '0'; if (lastDigit % 2 == 0) even.push_back(arr[i]); else odd.push_back(arr[i]); } string biggest = merge(even, odd); return biggest; } int main() { vector<string> arr; arr.push_back("17"); arr.push_back("80"); arr.push_back("99"); arr.push_back("27"); arr.push_back("14"); arr.push_back("22"); int n = arr.size(); cout<<"Biggest possible number from the array is = "<<largestNumber(arr, n); return 0; }
输出
Biggest possible number from the array is = 801799271422
广告