|
| 1 | +package CIS_Github; |
| 2 | +import java.util.List; |
| 3 | + |
| 4 | +/*A monotonic array is an array that has elements that |
| 5 | +are either always increasing or always decreasing. |
| 6 | + |
| 7 | +Example: [2,4,6,8] (Always increasing; Monotonic) {True} |
| 8 | +Example: [9,8,6,4] (Always decreasing; Monotonic) {True} |
| 9 | +Example: [4,2,8,7] (Neither always increasing nor decreasing) {False} |
| 10 | +*/ |
| 11 | + |
| 12 | +public class Mono { |
| 13 | + //Function to test if list is monotonic |
| 14 | + public static boolean isMonotonic(List<Integer> nums) { |
| 15 | + //Checks that list is always increasing |
| 16 | + boolean increasing = true; |
| 17 | + //Checks that list is always decreasing |
| 18 | + boolean decreasing = true; |
| 19 | + |
| 20 | + //Iterates through list to update boolean flag based on +/- |
| 21 | + for (int i = 0; i < nums.size() - 1; i++) { |
| 22 | + //If first number is less than the next, it is not increasing |
| 23 | + if (nums.get(i) < nums.get(i + 1)) { |
| 24 | + decreasing = false; |
| 25 | + } |
| 26 | + ////If first number is more than the next, it is not decreasing |
| 27 | + if (nums.get(i) > nums.get(i + 1)) { |
| 28 | + increasing = false; |
| 29 | + } |
| 30 | + } |
| 31 | + //List will return if monotonic |
| 32 | + return increasing || decreasing; |
| 33 | + } |
| 34 | + //Test case for isMonotonic function |
| 35 | + public static void main(String[] args) { |
| 36 | + System.out.println(isMonotonic(List.of(75, 64, 45, 36))); // Output: true |
| 37 | + System.out.println(isMonotonic(List.of(35, 45, 65, 85))); // Output: true |
| 38 | + System.out.println(isMonotonic(List.of(100, 56, 89))); |
| 39 | + System.out.println(isMonotonic(List.of(58394, 134569, 89002))); |
| 40 | + } |
| 41 | +} |
0 commit comments