ได้รับอาร์เรย์ขนาด N และช่วง [L, R] (1-based indexing) ต้องการนับจำนวนสมาชิกที่มีค่าน้อยที่สุดในช่วงนี้
ตัวอย่าง
อินพุต: arr[] = {1, 2, 3, 0, 3, 2, 0, 1}, N = 8, L = 2, R = 5
เอาต์พุต: 1
คำอธิบาย: ช่วง index 1-4 (0-based): {2, 3, 0, 3} ค่าน้อยสุด = 0 ปรากฏ 1 ครั้ง
อินพุต: L = 3, R = 8
เอาต์พุต: 2
คำอธิบาย: ช่วง index 2-7: {3, 0, 3, 2, 0, 1} ค่าน้อยสุด = 0 ปรากฏ 2 ครั้ง
แนวทาง
- ตรวจสอบช่วงถูกต้อง (L≥1, R≤N)
- วนหาค่าน้อยที่สุดในช่วง [L-1, R-1] (0-based)
- วนนับจำนวนที่เท่ากับค่าน้อยที่สุด
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
int countSmallest(int arr[], int n, int l, int r) {
int smallest = arr[l-1];
int count = 0;
if (l < 1 || r > n) return 0;
for (int i = l-1; i < r; i++) {
if (arr[i] < smallest) smallest = arr[i];
}
for (int i = l-1; i < r; i++) {
if (arr[i] == smallest) ++count;
}
return count;
}
int main() {
int arr[] = {3, 2, 1, 1, 2, 3};
int n = 6;
int L = 1, R = 5;
cout << endl << "Count of smallest in range: " << countSmallest(arr, n, L, R);
L = 3, R = 4;
cout << endl << "Count of smallest in range: " << countSmallest(arr, n, L, R);
return 0;
}
ผลลัพธ์
Count of smallest in range: 2 Count of smallest in range: 2