Maximum in Struct Array
Problem Description​
Given a struct array of type height, having two elements feet and inches. Find the maximum height
among n heights, where height is calculated sum of feet and inches
after converting feet
into inches
.
Examples​
Example 1:
Input:
n = 2 h1 -> {1 2} h2 -> {2 1}
Output:
25
Explanation:
(1, 2) and (2, 1) are respective given heights.After converting both heigths in to inches,we get 14 and 25 as respective heights.So, 25 is the maximum height.
Example 2:
Input:
n = n = 3 h1 -> {3 2} h2 -> {2 3} h3 ->{1 2}
Output:
38
Explanation:
(3, 2), (2,3) and (1, 2) are respective given heights.After converting both heigths in to inches,we get 38,27 and 14 as respective heights.So, 38 is the maximum height.
Constraints​
1 ≤ n ≤ 10^5
Solution for Maximum in Struct Array​
Code in Different Languages​
- Python
- Java
- C++
class Height:
def __init__(self, feet, inches):
self.feet = feet
self.inches = inches
def findMax(arr, n):
ans = [0] * n
max_height = 0
for i in range(n):
ans[i] = arr[i].feet * 12 + arr[i].inches
for height in ans:
if height > max_height:
max_height = height
return max_height
# Example usage
arr = [Height(5, 9), Height(6, 2), Height(5, 11)]
n = len(arr)
print(findMax(arr, n)) # Output: 74 (6 feet 2 inches)
class Height {
int feet;
int inches;
public Height(int feet, int inches) {
this.feet = feet;
this.inches = inches;
}
}
public class Main {
public static int findMax(Height[] arr, int n) {
int[] ans = new int[n];
int max = 0;
for (int i = 0; i < n; i++) {
ans[i] = arr[i].feet * 12 + arr[i].inches;
}
for (int i = 0; i < n; i++) {
if (ans[i] > max) {
max = ans[i];
}
}
return max;
}
public static void main(String[] args) {
Height[] arr = {new Height(5, 9), new Height(6, 2), new Height(5, 11)};
int n = arr.length;
System.out.println(findMax(arr, n)); // Output: 74 (6 feet 2 inches)
}
}
int findMax(Height arr[], int n) {
// Code here
int ans[n];
int max = 0;
for(int i=0;i<n;i++){
ans[i] = arr[i].feet*12 + arr[i].inches;
}
for(int i=0;i<n;i++){
if(ans[i]>max) max=ans[i];
}
return max;
}
References​
- GeekForGeeks Problem: Maximum in Struct Array