ในปัญหานี้ เราได้รับอาร์เรย์ของตัวเลขและเราต้องหาค่าที่ใหญ่ที่สุดที่สามารถทำได้โดยการเปลี่ยนค่าเหล่านี้ด้วยวิธีใดวิธีหนึ่ง เงื่อนไขในการจัดเรียงคือ ลำดับของเลขคู่และเลขคี่จะยังคงเหมือนเดิม กล่าวคือ ลำดับของเลขคู่ทั้งหมดไม่สามารถเปลี่ยนแปลงได้
มาดูตัวอย่างเพื่อทำความเข้าใจแนวคิดกันดีกว่า
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 มาก่อนในลำดับเลขคี่ ดังนั้นเราจึงพิจารณา 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