We are given an array containing integer elements and the task is to firstly calculate the subarray out of the given array and then check whether the elements in a subarray are in increasing order or not. If yes, then we will consider the subarray else it will be discarded.
The approach here is to stop further checking the subarray if the elements in 0th and 1th position are not in increasing order.
Input: int a[] = {1, 7, 5}
Output: Count of strictly increasing subarrays is 1
Explanation - The possible subarrays include {1,7,5}, {1,7}, {7,5} where {1,7} is the only array which is in strictly increasing order.
Input: int a[] = {1, 2, 7, 10}
Output: Count of strictly increasing subarrays is 6
Explanation - The possible subarrays include {{1, 2}, {1, 2, 7}, {1, 2, 7, 10},{2, 7}, {2, 7, 10} and {7, 10} and all are in strictly increasing order.
import java.util.*; class testqwe { static int MAX = 4; static int a[] = new int[MAX]; static Scanner scan = new Scanner(System.in); static int countIncSubarrays(int a[], int n) { int count = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (a[j] > a[j - 1]) count++; else break; } } return count; } public static void main(String[] args) { for (int i = 0; i < a.length; i++) { a[i] = scan.nextInt(); //1,2,7,0 } int result = countIncSubarrays(a, a.length); System.out.println("Count of strictly increasing subarrays is " + result); } }
If we run the above code it will generate the following output −
Count of strictly increasing subarrays is 6