Leetcode 2496. Maximum Value of a String in an Array
You are given an array of strings strs
. Each string contains only digits or only lowercase English letters.
strs
that corresponds to the maximum value.Return the maximum value among all the strings in strs
.
public class Solution {
public int maximumValue(String[] strs) {
int maxValue = Integer.MIN_VALUE;
for (String str : strs) {
int currentValue;
if (str.chars().allMatch(Character::isDigit)) {
// The string consists of only digits
currentValue = Integer.parseInt(str);
} else {
// The string consists of only lowercase English letters
currentValue = str.length();
}
// Update maxValue if currentValue is greater
if (currentValue > maxValue) {
maxValue = currentValue;
}
}
return maxValue;
}
public static void main(String[] args) {
Solution solution = new Solution();
// Sample test cases
String[] test1 = {"123", "abc", "4567", "abcd"};
System.out.println(solution.maximumValue(test1)); // Output: 4567
String[] test2 = {"99", "aa", "10", "b"};
System.out.println(solution.maximumValue(test2)); // Output: 99
}
}
Time Complexity: O(n), where n is the total number of characters in all strings combined. The main contributor to this complexity is iterating through each string and checking if all characters are digits (which is O(m) for each string of length m).
Space Complexity: O(1), as we are only using a few variables to track the current and maximum values. No extra data structures are being used that scale with input size.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?