Leetcode 2496. Maximum Value of a String in an Array
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.
strs
?strs
?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;
}
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.
stoi
and compare it with maxValue
.maxValue
.maxValue
.n
is the number of strings in the array, and m
is the average length of the strings. The complexity arises from needing to check each character of every string to determine if it’s numeric and then either converting to integer or measuring length.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?