Given an array arr[] of size N (1 ≤ N ≤ 105), the task is to find the number of ways to select a triplet i, j and k such that i < j < k and the product arr[i] * arr[j] * arr[k] is positive.
Note: Each triplet can consist of atmost one negative element.
Examples:
Input: arr[] = { 2, 5, -9, -3, 6}
Output: 1
Explanation: The total number ways to obtain a triplet i, j and k to satisfy given conditions is 1 {0, 1, 4}.Input : arr[] = {2, 5, 6, -2, 5}
Output : 4
Explanation: The total number ways to obtain a triplet i, j and k to satisfy given conditions are 4 {0, 1, 2}, {0, 1, 4}, {1, 2, 4} and {0, 2, 4}.
Approach: All possible combinations of a triplet are as follows:
- # negative elements or 2 negative elements and 1 positive elements. Both these combinations cannot be considered as the maximum allowed negative elements in a triplet is 1.
- 2 negative (-ve) elements and 1 positive ( +ve ) element. Since the product of the triplet will be negative, the triplet cannot be considered.
- 3 positive elements.
Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++
// C++ Program to implement // the above approach #include <bits/stdc++.h> using namespace std; // Function to calculate // possible number of triplets long long int possibleTriplets(int arr[], int N) { int freq = 0; // counting frequency of positive numbers // in array for (int i = 0; i < N; i++) { // If current array // element is positive if (arr[i] > 0) { // Increment frequency freq++; } } // Select a triplet from freq // elements such that i < j < k. return (freq * 1LL * (freq - 1) * (freq - 2)) / 6; } // Driver Code int main() { int arr[] = { 2, 5, -9, -3, 6 }; int N = sizeof(arr) / sizeof(arr[0]); cout << possibleTriplets(arr, N); return 0; } |
1
Time Complexity : O(N)
Auxiliary Space : O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

