Maximum Value of a String in an Array


class Solution:
    def maximumValue(self, strs: list[str]) -> int:
        return max(len(s) if any(c.isalpha() for c in s) else int(s)
                   for s in strs)

Problem Description

Welcome to the world of strings, where numbers and letters play a game of hide and seek! The problem at hand is to find the maximum value of a string in an array. But wait, there’s a twist! If the string contains any letters, its value is determined by its length. If it’s just a number, well, it’s worth its face value.

Imagine you’re at a party, and you have a bunch of friends (strings) who are either super tall (long strings) or just short and sweet (numbers). Your job is to figure out who’s the tallest friend in the room. Spoiler alert: if your friend is just a number, you can’t measure their height, but you can still appreciate their numerical value!

Approach

The approach here is as straightforward as it gets. For each string in the array, we check if it contains any alphabetic characters. If it does, we take its length as its value. If it’s just a number, we convert it to an integer. Finally, we return the maximum value found among all the strings. It’s like a talent show where everyone gets judged based on their unique skills!

Time and Space Complexity

  • Time Complexity: O(n * m), where n is the number of strings and m is the average length of the strings. This is because we potentially check each character in each string.
  • Space Complexity: O(1), as we are using a constant amount of space for our calculations.

Real-World Example

Let’s say you’re at a grocery store, and you have a list of items. Some items are just numbers (like “5” for 5 apples), while others are descriptions (like “Bananas”). You want to know which item has the highest value. In this case, the bananas would be valued by their length (8), while the apples would just be valued at 5. The maximum value here would be 8, and you’d know that bananas are the star of the show!

Similar Problems