Advertisement
rajeshinternshala

Untitled

Jan 13th, 2024
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.39 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class BitonicSubsequences {
  4.     private static final int MOD = 1000000007; // 1e9+7
  5.  
  6.     public static int countBitonicSubsequences(int[] arr) {
  7.         int n = arr.length;
  8.         int[] increasing = new int[n];
  9.         int[] decreasing = new int[n];
  10.         Arrays.fill(increasing, 0);
  11.         Arrays.fill(decreasing, 0);
  12.  
  13.         // Count increasing subsequences
  14.         for (int i = 0; i < n; i++) {
  15.             for (int j = 0; j < i; j++) {
  16.                 if (arr[j] < arr[i]) {
  17.                     increasing[i] = (increasing[i] + increasing[j] + 1) % MOD;
  18.                 }
  19.             }
  20.         }
  21.  
  22.         // Count decreasing subsequences
  23.         for (int i = n - 1; i >= 0; i--) {
  24.             for (int j = i + 1; j < n; j++) {
  25.                 if (arr[j] < arr[i]) {
  26.                     decreasing[i] = (decreasing[i] + decreasing[j] + 1) % MOD;
  27.                 }
  28.             }
  29.         }
  30.  
  31.         // Count bitonic subsequences
  32.         long count = 0;
  33.         for (int i = 1; i < n - 1; i++) {
  34.             count = (count + (long)increasing[i] * decreasing[i]) % MOD;
  35.         }
  36.  
  37.         return (int)count;
  38.     }
  39.  
  40.     public static void main(String[] args) {
  41.         int[] arr = {1, 2, 3, 2, 1};
  42.         int result = countBitonicSubsequences(arr);
  43.         System.out.println("The number of bitonic subsequences is: " + result);
  44.     }
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement