LeetCode 2496: Maximum Value of a String in an Array

ArrayString

Problem Description

Explanation:

To solve this problem, we need to iterate through each string in the array and calculate the value of each string based on the given rules. We will keep track of the maximum value found so far and return it as the result.

  1. Iterate through each string in the array.
  2. If the string consists only of digits, convert it to an integer and update the maximum value if it is greater.
  3. If the string consists of letters and digits, calculate its length and update the maximum value if it is greater.
  4. Finally, return the maximum value found.

Time Complexity: O(n) where n is the number of strings in the input array.

Space Complexity: O(1) as we are using constant extra space.

:

Solutions

class Solution {
    public int getMaxValue(String[] strs) {
        int maxValue = 0;
        
        for (String str : strs) {
            int val = 0;
            if (str.matches("\\d+")) {
                val = Integer.parseInt(str);
            } else {
                val = str.length();
            }
            maxValue = Math.max(maxValue, val);
        }
        
        return maxValue;
    }
}

Loading editor...