Count of triplets of numbers 1 to N such that middle element is always largest
Last Updated :
09 Feb, 2022
Given an integer N, the task is to count the number of ways to arrange triplets (a, b, c) within [1, N] in such a way such that the middle element is always greater than left and right elements.
Example:
Input: N = 4
Output: 8
Explanation
For the given input N = 4 number of possible triplets are:{1, 3, 2}, {2, 3, 1}, {2, 4, 3}, {3, 4, 2}, {1, 4, 3}, {3, 4, 1}, {2, 4, 1}, {1, 4, 2}.
Input: 10
Output: 240
Naive Approach: Check for all triplets whether it satisfies the given condition using three nested loops and keep incrementing their count every time a triplet satisfies the condition.
Time Complexity: O( N3 )
Auxiliary Space: O( 1 )
Efficient Approach:
- Check all the possibilities for middle element and try to find the number of possible arrangements keeping each of them fixed one by one.
- We can observe that all the numbers between [3, N] can occupy the middle slot.
Possible arrangements for every middle element:
On placing 3 at the middle, only 2 ( = 2 * 1) possible arrangements exist {1, 3, 2} and {2, 3, 1}.
On placing 4 at the middle, 6 ( = 3 * 2) possible arrangements exist {1, 4, 3}, {1, 4, 2}, {2, 4, 1}, {2, 4, 3}, {3, 4, 1} and {3, 4, 2}.
On placing 5 at the middle, 12 ( = 4 * 3) possible arrangements exist.
.
.
.
On placing N – 1 at the middle, (N-2) * (N-3) possible arrangements exist.
On placing N at the middle, (N-1) * (N-2) possible arrangements exist.
Thus, Total possible arrangements = ( N * (N-1) * (N-2)) / 3
Below is the implementation of the above approach.
C++
#include <bits/stdc++.h>
using namespace std;
int findArrangement( int N)
{
if (N < 3)
return 0;
return ((N) * (N - 1) * (N - 2)) / 3;
}
int main()
{
int N = 10;
cout << findArrangement(N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static int findArrangement( int N)
{
if (N < 3 )
return 0 ;
return ((N) * (N - 1 ) * (N - 2 )) / 3 ;
}
public static void main(String[] args)
{
int N = 10 ;
System.out.println(findArrangement(N));
}
}
|
Python3
def findArrangement(N):
if (N < 3 ):
return 0 ;
return ((N) * (N - 1 ) * (N - 2 )) / / 3 ;
N = 10 ;
print (findArrangement(N));
|
C#
using System;
class GFG{
static int findArrangement( int N)
{
if (N < 3)
return 0;
return ((N) * (N - 1) * (N - 2)) / 3;
}
public static void Main()
{
int N = 10;
Console.Write(findArrangement(N));
}
}
|
Javascript
<script>
function findArrangement(N)
{
if (N < 3)
return 0;
return ((N) * (N - 1) * (N - 2)) / 3;
}
let N = 10;
document.write(findArrangement(N));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...