algoadvance

Leetcode 2496. Maximum Value of a String in an Array

Problem Statement

You are given an array of strings strs. Each string contains only digits or only lowercase English letters.

Return the maximum value among all the strings in strs.

Clarifying Questions

  1. How should we treat strings that contain a mix of both digits and lowercase letters?
    • The problem specifies that strings contain either digits or lowercase letters, so mixed strings are out of scope.
  2. Are leading zeros in digit strings valid and should they be considered?
    • Yes, if a string contains only digits, it will be evaluated as its numeric value, so leading zeros should be considered correctly (e.g., “007” is 7).

Strategy

  1. We will iterate through the array of strings.
  2. For each string, determine whether it consists of digits or alphabetic characters.
  3. Evaluate its value accordingly:
    • If the string is numeric, convert it to an integer.
    • If the string is alphabetic, compute its length.
  4. Keep track of the maximum value encountered during the iteration.
  5. Finally, return the maximum value.

Code

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

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI