algoadvance

Leetcode 3200. Maximum Height of a Triangle

Problem Statement

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.

Clarifying Questions

  1. Is there any constraint on the length of the string s?
    • Yes, let’s assume the length of s is n where 1 <= n <= 10^4.
  2. Can the string s be empty?
    • No, based on the constraints, the minimum length of s is 1.
  3. Are we only concerned with lowercase English letters in s?
    • Yes, the string s only consists of lowercase English letters.

Strategy

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:

  1. Create an array to count the frequency of each character in the string s.
  2. Traverse the array to find the maximum frequency.
  3. The maximum frequency will be the height of the tallest triangle that can be made with s as the base.

Code

#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;
}

Time Complexity

The time complexity of this solution is (O(n)), where (n) is the length of the string (s). This includes:

  1. Traversing the string to compute the frequency of each character.
  2. Finding the maximum element in the frequency array.

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.

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