algoadvance

Leetcode 2496. Maximum Value of a String in an Array

Problem Statement

You are given an array of strings strs. Each string in the array consists of either a positive integer without leading zeros or a mix of digits and lowercase English letters.

Your task is to find the maximum value among all the strings in the array. The value of a string is defined as follows:

Return the maximum value of a string in the array.

Clarifying Questions

  1. Input Constraints:
    • What is the size range for the list strs?
    • What will be the maximum length of any string in the strs?
  2. Edge Cases:
    • How should the function behave if an empty array is passed?
    • Will there be any strings with leading zeros that might be interpreted incorrectly?

Code

Here is the C++ solution to address the problem:

#include <iostream>
#include <vector>
#include <string>
#include <algorithm> // for std::max
#include <cctype> // for std::isdigit

using namespace std;

class Solution {
public:
    int maximumValue(vector<string>& strs) {
        int maxValue = INT_MIN;
        
        // Iterate over each string in the vector
        for (const string& s : strs) {
            bool isNumeric = true;
            
            // Check if the string is a pure number
            for (char c : s) {
                if (!isdigit(c)) {
                    isNumeric = false;
                    break;
                }
            }
            
            if (isNumeric) {
                // If it is a number, convert it to an integer and compare
                maxValue = max(maxValue, stoi(s));
            } else {
                // If it contains any letters, compare its length
                maxValue = max(maxValue, static_cast<int>(s.size()));
            }
        }
        
        return maxValue;
    }
};

int main() {
    Solution solution;
    
    vector<string> strs1 = {"123", "abc", "456", "de"};
    cout << "Maximum value: " << solution.maximumValue(strs1) << endl; // Should output 456 (integer value)
    
    vector<string> strs2 = {"a", "ab", "abc", "abcdef"};
    cout << "Maximum value: " << solution.maximumValue(strs2) << endl; // Should output 6 (length of "abcdef")
    
    return 0;
}

Strategy

  1. Initialization: Start by initializing a variable maxValue to store the maximum value found so far. Set it to INT_MIN to ensure any valid number or length will be larger initially.

  2. Iteration: Iterate over each string in the array:
    • Check if Numeric: Use a helper check within the loop to determine if all characters of the string are digits.
    • Calculate Value:
      • If the string contains only digits, convert it to an integer using stoi and compare it with maxValue.
      • If the string contains any letters, calculate its length and compare it with maxValue.
  3. Return Result: After completing the iteration, return the maxValue.

Time Complexity

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