Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

นับ Subarray ที่สมาชิกทุกตัวมากกว่า K ใน C++

เราได้รับอาร์เรย์ arr[] และตัวเลข K เป้าหมายคือนับ subarray ที่สมาชิกทุกตัวมีค่ามากกว่า K

ตัวอย่าง

อินพุต: arr[] = {2, 2, 1, 1, 1, 5}, K = 1

เอาต์พุต: 4

คำอธิบาย: [2], [2], [5], [2,2]

อินพุต: arr[] = {3, 4, 5, 6}, K = 2

เอาต์พุต: 10

คำอธิบาย: ทุก subarray เป็นไปได้ทั้งหมด 10 ตัว

แนวทางการแก้ปัญหา

วนลูปอาร์เรย์ นับ consecutive elements ที่ > K ใช้สูตร count × (count + 1) / 2 สำหรับแต่ละกลุ่ม

การนำไปใช้ (Implementation)

#include <bits/stdc++.h>
using namespace std;

int sub_greater_k(int arr[], int size, int k) {
    int count = 0;
    int total = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] > k) {
            count++;
        } else {
            total += count * (count + 1) / 2;
            count = 0;
        }
    }
    if (count) {
        total += count * (count + 1) / 2;
    }
    return total;
}

int main() {
    int arr[] = {2, 4, 6, 1, 3, 7, 9};
    int size = sizeof(arr) / sizeof(arr[0]);
    int k = 7;
    cout << "Count of subarrays with all elements greater than K are: " << sub_greater_k(arr, size, k);
    return 0;
}

เอาต์พุต

Count of subarrays with all elements greater than K are: 1