ให้อาเรย์และช่วงดัชนี lower, upper นับจำนวนคู่ติดกันที่เท่ากันในช่วง
ตัวอย่าง:
Input: arr = [1, 2, 2, 2, 3, 3, 4], lower = 1, upper = 5 Output: 3
อัลกอริทึม
- กำหนดอาเรย์และช่วง
- count = 0
- วน i = lower ถึง upper-1:
- ถ้า arr[i] == arr[i+1] count++
- คืนค่า count
การเขียนโปรแกรม C++
#include <bits/stdc++.h> using namespace std; int getEqualElementsCount(int arr[], int n, int lower, int upper) { int count = 0; for (int i = lower; i < upper; i++) { if (arr[i] == arr[i + 1]) count++; } return count; } int main() { int arr[] = { 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5 }; int n = 15; cout << getEqualElementsCount(arr, 15, 1, 15) << endl; return 0; }
ผลลัพธ์
10