- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the count of Strictly decreasing Subarrays in C++
Suppose we have an array A. And we have to find the total number of strictly decreasing subarrays of length > 1. So if A = [100, 3, 1, 15]. So decreasing sequences are [100, 3], [100, 3, 1], [15] So output will be 3. as three subarrays are found.
The idea is find subarray of len l and adds l(l – 1)/2 to result.
Example
#include<iostream> using namespace std; int countSubarrays(int array[], int n) { int count = 0; int l = 1; for (int i = 0; i < n - 1; ++i) { if (array[i + 1] < array[i]) l++; else { count += (((l - 1) * l) / 2); l = 1; } } if (l > 1) count += (((l - 1) * l) / 2); return count; } int main() { int A[] = { 100, 3, 1, 13, 8}; int n = sizeof(A) / sizeof(A[0]); cout << "Number of decreasing subarrys: " << countSubarrays(A, n); }
Output
Number of decreasing subarrys: 4
Advertisements