Programmers / Maximum and Minimum Values

Programmers / Maximum and Minimum Values

Problem

Solution 1

 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
class Solution {
    public String solution(String s) {
        // Convert string to int
        String[] splits = s.split(" ");
        int[] integers = new int[splits.length];
        for (int i = 0; i < splits.length; i++) {
            integers[i] = Integer.parseInt(splits[i]);
        }
        
        // Find min
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] < min) {
                min = integers[i];
            }
        }
        
        // Find max
        int max = Integer.MIN_VALUE;
        for (int i = 0; i < integers.length; i++) {
            if (integers[i] > max) {
                max = integers[i];
            }
        }
        
        return min + " " + max;
    }
}
Solution 1
  • Description
    • Split the string by spaces and convert to integers
    • Return the maximum and minimum values of the converted numbers
  • Time Complexity
    • O(spaceCount(s))
    • For loop iterates as many times as the number of numbers in the string
  • Space Complexity
    • O(spaceCount(s))
    • Array size allocation proportional to the number of numbers in the string