-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMaxElement.java
More file actions
42 lines (37 loc) Β· 1.11 KB
/
Copy pathMaxElement.java
File metadata and controls
42 lines (37 loc) Β· 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package day5;
public class MaxElement {
/*
time complexity: O(1)
space complexity: O(1)
*/
public static void main(String[] args) {
// representing infinity in java βΎ
// System.out.println(Integer.MIN_VALUE);
// System.out.println(Integer.MAX_VALUE);
System.out.println(maximum(new int[] {1, 2, 3, 4}));
System.out.println(maximum(new int[] {1, 2, 3, 4, 5}));
System.out.println(maximum(new int[] {}));
System.out.println(maximum(new int[] {-100, -3, -2, -56, -45, 10, 1}));
// to update array we can't use foreach loop
// for (int element : array) {
// element = 10;
// }
}
/*
{1, 2, 4, 5, 100, 4} --> 100
{-100, -90, 4, 3} --> 4
{} --> -Infinity
{-1, -2, -3} -->
time complexity: O(n)
space complexity: O(1)
*/
private static int maximum(int[] array) {
int max = Integer.MIN_VALUE;
for (int element : array) {
if (element > max) {
max = element;
}
}
return max;
}
}