ได้รับอาร์เรย์ N ตัว ค่าอยู่ในช่วง 0 ถึง N-1 ไม่เรียงลำดับ ต้องการแบ่งเป็นพาร์ติชันมากที่สุดที่แต่ละพาร์ติชันเรียงลำดับแยกได้ แล้วนำมาต่อกันได้อาร์เรย์เรียงลำดับสมบูรณ์
ข้อสังเกต
ในอาร์เรย์เรียงแล้ว Arr[i] = i ดังนั้นถ้าส่วนหนึ่งมีค่าสูงสุดเท่ากับ index สุดท้ายของส่วนนั้น ส่วนนั้นสามารถเป็นพาร์ติชันได้
ตัวอย่าง
อินพุต: Arr[] = {0, 3, 2, 1, 4, 5}
เอาต์พุต: 3
คำอธิบาย: พาร์ติชัน: [0,3,2,1], [4], [5] เรียงแต่ละชิ้นแล้วต่อกันได้ [0,1,2,3,4,5]
อินพุต: Arr[] = {5, 4, 3, 2, 1, 0}
เอาต์พุต: 1 (ต้องเรียงทั้งอาร์เรย์)
แนวทาง
- เก็บ maxx = ค่าสูงสุดที่เจอจนถึง index i
- ถ้า maxx == i → พบพาร์ติชัน ใหม่ เพิ่มตัวนับ
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int partitions(int arr[], int n) {
int count = 0;
int maxx = arr[0];
for (int i = 0; i < n; ++i) {
if (arr[i] > maxx) maxx = arr[i];
if (maxx == i) count++;
}
return count;
}
int main() {
int Num[] = {2, 1, 0, 4, 5, 3};
int len = 6;
cout << "Maximum partitions that can be sorted: " << partitions(Num, len);
return 0;
}
ผลลัพธ์
Maximum partitions that can be sorted: 18