Maximum Value of a String in an Array

Problem Description

So, you think you can just throw a bunch of strings into an array and expect them to magically tell you which one has the highest value? Well, think again! The “Maximum Value of a String in an Array” problem is here to remind you that not all strings are created equal.

Imagine you’re at a party, and everyone is trying to impress you with their best jokes. Some are just plain numbers trying to fit in, while others are witty strings full of puns and wordplay. Your job? Determine which one has the most “value.” In this case, the value is defined as the length of the string if it contains any alphabetic characters, or the integer value of the string if it’s purely numeric.

So, if you have an array like ["123", "hello", "4567", "world"], you need to figure out that “hello” and “world” are the real party animals here, with lengths of 5 and 5, while “123” and “4567” are just numbers trying to crash the party.

Code Solution


class Solution {
  public int maximumValue(String[] strs) {
    int ans = 0;
    for (final String s : strs)
      ans = Math.max(ans, s.chars().anyMatch(c -> Character.isAlphabetic(c)) ? s.length()
                                                                             : Integer.valueOf(s));
    return ans;
  }
}

Approach

The approach taken in the code is straightforward yet effective. It iterates through each string in the array and checks if it contains any alphabetic characters. If it does, the length of that string is considered its value. If it’s just a number, the integer value of that string is used instead. The maximum value found during this process is returned as the result.

Time and Space Complexity

Time Complexity: O(n * m), where n is the number of strings in the array and m is the average length of the strings. This is because we are checking each character in each string.

Space Complexity: O(1), as we are using a constant amount of space for the variables.

Real-World Example

Think of this problem like a talent show where contestants are either singers (strings with letters) or dancers (strings with numbers). The judges (your code) need to decide who has the most talent (value). If a contestant can sing, they get points for their performance length. If they can only dance, they get points based on their dance number. In the end, the contestant with the highest score wins!

Similar Problems

Two Sum Solution in Java