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