by BehindJava

Wap to find if a Given Array is Monotonic in Java

Home » interview » Wap to find if a Given Array is Monotonic in Java

In this blog, we are going to learn about writing a program to find if a given array is monotonic or not in Java.

Monotonic Array

An array is monotonic if it’s Monotone is increasing or decreasing.

Example:

Input: n=[1, 3, 3, 5, 6, 8, 12]
Output: True

Input: n=[12, 8, 6, 5, 3, 3, 1]
Output: True

Input: n=[1, 3, 3, 55, 3, 3, 1]
Output: False

public class MonotonicArray {

	public boolean isMonotone(int[] arr) {
		boolean isInc = true;
		boolean isDec = true;
		for (int i = 0; i < arr.length - 1; i++) {
			if (arr[i] > arr[i + 1])
				isInc = false;
			if (arr[i] < arr[i + 1])
				isDec = false;
		}
		return isInc || isDec;
	}

	public static void main(String args[]) {

		int[] array = { 1, 3, 3, 5, 6, 8, 12 };
		int[] array1 = { 12, 8, 6, 5, 3, 3, 1 };
		int[] array2 = { 1, 3, 3, 55, 3, 3, 1 };

		MonotonicArray ma = new MonotonicArray();
		System.out.println("Is Monotone: " + ma.isMonotone(array));
		System.out.println("Is Monotone: " + ma.isMonotone(array1));
		System.out.println("Is Monotone: " + ma.isMonotone(array2));
	}}

Output:

Is Monotone: true
Is Monotone: true
Is Monotone: false