Write a Boolean method that accepts an integer array as input This method should
ID: 3904789 • Letter: W
Question
Write a Boolean method that accepts an integer array as input This method should return true if the array is a “mountain”, and false if it is not. An array is considered a mountain if it has only one peak. For example:
[1, 2, 3, 4, 7, 9, 5, 3, 1] is a mountain. The values increase to a maximum (9), and then decrease until the end of the array.
[1, 2, 3, 4, 3, 2, 5, 7, 8, 9, 4, 2] is NOT a mountain, because the values increase to 4, then decrease to 2, then increase back to 9, and finally decrease until the end. This array has two peaks.
Explanation / Answer
boolean isMountain(int arr[]){ int count = 0; for(int i = 0;i arr[i+1]){ count++; } } else if(i == arr.length-1){ if(arr[i] > arr[i-1]){ count++; } } else{ if(arr[i] > arr[i+1] && arr[i] > arr[i-1]){ count++; } } } if(count == 1){ return true; } else{ return false; } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.