알고리즘

Number of Senior Citizens

짬뽕얼큰하게 2025. 2. 4. 09:05

Leetcode Problem:

Summary

  • The problem requires to count the number of passengers who are strictly more than 60 years old based on their details.

Approach

  • The approach used is to iterate over the details array and check the age of each passenger by comparing the 11th character (gender) and 12th character (age) with the condition
  • If the gender is 'M' or 'O' and the age is greater than 60, or if the gender is 'F' and the age is 60 or greater, then the passenger is counted as a senior.

Complexity

  • O(n) where n is the number of passengers, as we are iterating over the details array once.

Explain

  • Here's a step-by-step explanation of the solution code: 1
  • Initialize a variable `ans` to store the count of seniors. 2
  • Iterate over the `details` array using a for loop. 3
  • Inside the loop, check the age of the current passenger by comparing the 11th character (gender) and 12th character (age) with the condition. 4
  • If the gender is 'M' or 'O' and the age is greater than 60, or if the gender is 'F' and the age is 60 or greater, then increment the `ans` variable. 5
  • Return the final count of seniors after iterating over the entire array.

Solution Code:


class Solution {
public:
    int countSeniors(vector& details) {
        int ans = 0;
        for(int i = 0 ; i < details.size(); i++){
            if(details[i][11] > '6'){
                ans++;
            } else if(details[i][11] =='6' && details[i][12] > '0'){
                ans++;
            }
        }
        return ans;
    }
};