Skip to content

Commit 09ba155

Browse files
committed
Merge branch 'build1' of https://github.com/SlyyJavii/TheAlgorithmJava into build1
2 parents 0c6e34b + 0896917 commit 09ba155

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

Monotonic Array Java Build 1.1

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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+
}

Montonic Python Build 1.0

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# https://leetcode.com/problems/monotonic-array/
2+
def is_monotonic(nums: list[int]) -> bool:
3+
"""
4+
Check if a list is monotonic.
5+
6+
>>> is_monotonic([1, 2, 2, 3])
7+
True
8+
>>> is_monotonic([6, 5, 4, 4])
9+
True
10+
>>> is_monotonic([1, 3, 2])
11+
False
12+
"""
13+
return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) or all(
14+
nums[i] >= nums[i + 1] for i in range(len(nums) - 1)
15+
)
16+
17+
18+
# Test the function with your examples
19+
if __name__ == "__main__":
20+
# Test the function with your examples
21+
print(is_monotonic([1, 2, 2, 3])) # Output: True
22+
print(is_monotonic([6, 5, 4, 4])) # Output: True
23+
print(is_monotonic([1, 3, 2])) # Output: False

0 commit comments

Comments
 (0)