เราได้รับ Circular Array ของตัวเลข (อาเรย์วนรอบ: สมาชิกแรกอยู่ติดกับสมาชิกสุดท้าย) แต่ละสมาชิกมีจำนวนหลักเท่าหรือต่างกัน เป้าหมายคือสร้างตัวเลขมากที่สุดโดยการต่อ (concatenate) ตัวเลข โดยอาจหมุน (rotate) ตำแหน่งสมาชิก เราทำได้โดยหาตัวเลขที่มีหลักหน่วย (leftmost digit) มากที่สุด ตัวเลขนั้นจะมาวางตำแหน่งแรก
- ถ้าอยู่ตำแหน่งแรกแล้ว ตัวอื่นต่อตามลำดับ 1 ถึง n-1
- ถ้าอยู่กลาง index i ตัว i+1 ถึง n-1 ต่อก่อน ตามด้วย 0 ถึง i-1
- ถ้าอยู่ตัวสุดท้าย ตัว 0 ถึง i-1 ต่อหลังมัน
อินพุต
Arr[] = {121, 43, 65, 32}
เอาต์พุต
Highest number: 653212143
คำอธิบาย − หลักหน่วยมากที่สุดคือ 6 (ของ 65) วาง 65 ก่อน ตามด้วย 32, 121, 43
อินพุต
Arr[] = {1101, 9, 321, 77}
เอาต์พุต
Highest number: 9321771101
คำอธิบาย − หลักหน่วยมากที่สุดคือ 9 วาง 9 ก่อน ตามด้วย 321, 77, 1101
วิธีการที่ใช้ในโปรแกรมด้านล่าง
- อาเรย์ arr[] เก็บตัวเลข
- ฟังก์ชัน Largest(int arr[], int n) พิมพ์ตัวเลขมากที่สุด
- maxx เก็บตัวเลขที่มีหลักหน่วยมากที่สุด เริ่มต้น 0
- pos เก็บ index ของ maxx
- ลูป i=0..n-1 หาหลักหน่วยของ arr[i] ด้วยการหาร 10 จนเหลือ 0 เศษสุดท้ายคือหลักหน่วย
- ถ้าหลักหน่วยมากกว่า maxx อัปเดต maxx และ pos
- พิมพ์ตัวเลขจาก pos ถึง n-1 แล้วตามด้วย 0 ถึง pos-1
ตัวอย่างโค้ด
#include <bits/stdc++.h>
using namespace std;
void Largest(int arr[], int n) {
int maxx = 0;
int pos = 0;
for (int i = 0; i < n; i++) {
int num = arr[i];
while (num != 0) {
int rem = num % 10;
num = num / 10;
if (num == 0) {
if (maxx < rem) {
maxx = rem;
pos = i;
}
}
}
}
cout << "Largest number by concatenation: ";
for (int i = pos; i < n; i++) cout << arr[i];
for (int i = 0; i < pos; i++) cout << arr[i];
}
int main() {
int Arr[] = {12, 34, 56, 98};
int size = 4;
Largest(Arr, size);
return 0;
}
ผลลัพธ์
Largest number by concatenation: 98123456