[Java Easy Approach, Linear Time] Valid Mountain Array - With Comments

Valid Mountain Array

Explanation

To solve this problem, let's focus on the premise that if it is a valid mountain, it has only one peak, :

// There is a peak if an element is greater than its right and left side: Ex: 5, 6, 5
arr[i - 1] < arr[i] && arr[i] > arr[i + 1]

So if we count how many peaks appear in the array we will know whether or not it is a valid mountain: if it has more than one peak it is not valid.

Below is the complete code:

class Solution {
    public boolean validMountainArray(int[] arr) {
		if(arr.length < 3) return false;
		int c = 0;
		// Let's not forget to consider the border cases
		// if the first element is greater than the second is not valid
		if(arr[0] > arr[1]) return false;
		// if the last element is greater than the penultimate, it is not valid either
		if(arr[arr.length - 1] > arr[arr.length-2]) return false;

		// the tour should start in the second and finish in the penultimate element of the array
		for(int i = 1; i < arr.length - 1; i++){
			if(arr[i - 1] < arr[i] && arr[i] > arr[i + 1]){
				c++; // add a peak 
			}
			if(arr[i] == arr[i - 1]) return false;
		}
		return c == 1; // only es a valid mountain if we've one peak
    }
}
Comments (3)