Leetcode 3200. Maximum Height of a Triangle
Given a string s
that consists of lowercase English letters, you are allowed to perform operations on the string. In each operation, you can select an index i
in the string s
and replace s[i]
with any lowercase English letter.
Your task is to determine the maximum height of any triangle that can be formed with the string s
as the base.
A triangle of height h
can be formed if there are at least h
occurrences of some character in s
.
Output the maximum height of such a triangle.
s
?
s
is n
where 1 <= n <= 10^4
.s
be empty?
s
is 1.s
?
s
only consists of lowercase English letters.To determine the maximum height of the triangle, we need to find the most frequent character in the string s
. The frequency of the most frequent character will determine the maximum possible height of the triangle.
Steps:
s
.s
as the base.#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int maxTriangleHeight(string s) {
vector<int> frequency(26, 0); // to store frequency of each character
for (char ch : s) {
frequency[ch - 'a']++;
}
int maxHeight = *max_element(frequency.begin(), frequency.end());
return maxHeight;
}
int main() {
string s;
cout << "Enter the string: ";
cin >> s;
int result = maxTriangleHeight(s);
cout << "The maximum height of the triangle is: " << result << endl;
return 0;
}
The time complexity of this solution is (O(n)), where (n) is the length of the string (s). This includes:
Both operations are linear in nature. The space complexity is (O(1)), as the extra space used (the frequency array) is constant and independent of the input size.
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?