Find max in struct array
Last Updated :
23 Apr, 2024
Given a struct array of type Height, find max
struct Height{
int feet;
int inches;
}
Question source : Microsoft Interview Experience Set 127 | (On-Campus for IDC)
The idea is simple, traverse the array, and keep track of max value
value of array element(in inches) = 12*feet + inches
Implementation:
CPP
// CPP program to return max
// in struct array
#include <iostream>
#include <climits>
using namespace std;
// struct Height
// 1 feet = 12 inches
struct Height {
int feet;
int inches;
};
// return max of the array
int findMax(Height arr[], int n)
{
int mx = INT_MIN;
for (int i = 0; i < n; i++) {
int temp = 12 * (arr[i].feet)
+ arr[i].inches;
mx = max(mx, temp);
}
return mx;
}
// driver program
int main()
{
// initialize the array
Height arr[] = {
{ 1, 3 },
{ 10, 5 },
{ 6, 8 },
{ 3, 7 },
{ 5, 9 }
};
int res = findMax(arr, 5);
cout << "max :: " << res << endl;
return 0;
}
Python3
# Python program to return max
# in list of dictionaries
# Importing the sys module for INT_MIN
import sys
# Dictionary to represent Height
# 1 feet = 12 inches
class Height:
def __init__(self, feet, inches):
self.feet = feet
self.inches = inches
# Function to return max of the list
def findMax(arr):
mx = -sys.maxsize - 1
for i in arr:
temp = 12 * i['feet'] + i['inches']
mx = max(mx, temp)
return mx
# Driver program
if __name__ == "__main__":
# Initialize the list
arr = [
{'feet': 1, 'inches': 3},
{'feet': 10, 'inches': 5},
{'feet': 6, 'inches': 8},
{'feet': 3, 'inches': 7},
{'feet': 5, 'inches': 9}
]
res = findMax(arr)
print("max ::", res)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...