กำหนดอาร์เรย์ arr[ ] ของจำนวนเต็มบวก เป้าหมายคือการหาจำนวนอาร์เรย์ย่อยของ arr[ ] ที่มีค่าเฉลี่ยขององค์ประกอบมากกว่าค่าเฉลี่ยขององค์ประกอบที่เหลือของ arr[ ] ที่ไม่มีอยู่ในนั้น
ตัวอย่าง
อินพุต
arr[ ] = { 3, 2, 4 } ผลลัพธ์
Count of number of sub-arrays such that the average of elements present in the sub−array is greater than that do not present in the sub−array are: 2
คำอธิบาย
The subarrays are − [ 3 ], [ 2 ], [ 4 ], [ 3,2 ], [ 2,4 ], [ 3,2,4 ]. Average of [ 4 ] is 4 which is more than the average of [ 2,3 ]. Average of [ 3,2,4 ] is 3 which is more than the average of [ ]
อินพุต
arr[ ] = { 3, 3, 3 } ผลลัพธ์
Count of number of sub−arrays such that the average of elements present in the sub−array is greater than that do not present in the sub−array are: 1
คำอธิบาย
The subarrays are − [ 3 ], [ 3 ], [ 3 ], [ 3,3 ], [ 3,3 ], [ 3,3,3 ]. Average of [ 3,3,3 ] is 3 which is more than the average of [ ]
แนวทางที่ใช้ในโปรแกรมด้านล่างมีดังนี้ −
ในแนวทางนี้ ให้สร้างอาร์เรย์ผลรวมนำหน้าซึ่งจะเก็บผลรวมขององค์ประกอบไม่เกินดัชนี i ใน new_arr[i] ตอนนี้ เรามีผลรวมไม่เกินองค์ประกอบก่อนหน้า จากนั้นคำนวณผลรวมไม่เกิน arr[i] และนับองค์ประกอบเป็น j−i+1 แล้วคำนวณค่าเฉลี่ย
-
รับอาร์เรย์ arr[] เป็นอินพุต
-
ฟังก์ชัน count(int arr[], int size) รับ arr[ ] และคืนค่าจำนวนของ sub−array เพื่อให้ค่าเฉลี่ยขององค์ประกอบที่มีอยู่ใน sub−array มีค่ามากกว่าที่ไม่มีอยู่ใน sub−array
-
ใช้อาร์เรย์ new_arr[ขนาด] เพื่อเก็บผลรวมขององค์ประกอบดัชนีก่อนหน้า
-
ข้ามจาก i=0 ถึง i
-
ตอนนี้สำรวจ new_arr[ ] โดยใช้สองลูป
-
ตอนนี้คำนวณ Total_1 เป็นผลรวมของอาร์เรย์ย่อยก่อนหน้า และองค์ประกอบในนั้นนับ _1.
-
คำนวณ total_2 เป็นผลรวมของอาร์เรย์ย่อยถัดไปและองค์ประกอบในนั้นเป็น count_2
-
คำนวณค่าเฉลี่ยเป็น check_1 =total_1 / count_1; และ check_2 =total_2 /count_2;
-
หากค่าเฉลี่ย check_1> check_2 การเพิ่มขึ้นจะนับ
-
ที่ส่วนท้ายของ for loop จะนับเป็นผลลัพธ์
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int count(int arr[], int size){
int count = 0;
int new_size = size + 1;
int new_arr[new_size] = { 0 };
for (int i = 1; i < new_size; i++){
new_arr[i] = new_arr[i − 1] + arr[i − 1];
}
for (int i = 1; i < new_size; i++){
for (int j = i; j < new_size; j++){
int total_1 = new_arr[j] − new_arr[i − 1];
int count_1 = j − i + 1;
int total_2 = new_arr[size] − total_1;
int count_2 = 0;
if((size − count_1) == 0){
count_2 = 1;
} else {
count_2 = size − count_1;
}
int check_1 = total_1 / count_1;
int check_2 = total_2 / count_2;
if (check_1 > check_2){
count++;
}
}
}
return count;
}
int main(){
int arr[] = { 2, 6, 2, 4 };
int size = sizeof(arr) / sizeof(arr[0]);
cout<<"Count of number of sub−arrays such that the average of elements present in
the sub−array "<< "is greater than that not present in the sub−array are: "<<count(arr, size);
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดข้างต้น มันจะสร้างผลลัพธ์ต่อไปนี้ -
Count the number of sub−arrays such that the average of elements present in the subarrayis greater than that not present in the sub-array are: 6