An e-commerce website tracks which products are purchased each day.
The product that sells the most on a given day becomes the featured product for the next day.
π Rules:
- Count how many times each product appears in the list.
- The product with the highest number of purchases is selected.
- If there is a tie (multiple products have the same highest count):
- Sort those product names in alphabetical order (A β Z).
- Choose the last product in that sorted list.
π― Task:
Given a list of product names purchased during the day, determine which product will be the featured product.
π₯ Input Format:
- The first line contains an integer
n(number of products). - The next
nlines each contain a product name (string).
π€ Output Format:
- Print a single string β the featured product.
βοΈ Constraints:
- 1β€nβ€104
π Example 1:
Input:
6
redShirt
greenPants
redShirt
orangeShoes
blackPants
blackPants
Explanation:
- redShirt β 2 times
- blackPants β 2 times
- greenPants, orangeShoes β 1 time
Tie between:
- blackPants, redShirt
Sorted:
blackPants
redShirt
π Last = redShirt
Output:
redShirt
π Example 2:
Input:
9
yellowShirt
redHat
blackShirt
bluePants
redHat
pinkHat
blackShirt
yellowShirt
greenPants
Explanation:
- yellowShirt β 2
- blackShirt β 2
- redHat β 2
- greenPants β 2
Sorted:
blackShirt
greenPants
redHat
yellowShirt
π Last = yellowShirt
Output:
yellowShirt
C Program
#include <stdio.h>
#include <string.h>
#define MAX 10000
#define LEN 100
int main() {
int n;
scanf("%d", &n);
char products[MAX][LEN];
for (int i = 0; i < n; i++) {
scanf("%s", products[i]);
}
char unique[MAX][LEN];
int count[MAX] = {0};
int uniqueCount = 0;
// Step 1: Count frequency
for (int i = 0; i < n; i++) {
int found = -1;
for (int j = 0; j < uniqueCount; j++) {
if (strcmp(products[i], unique[j]) == 0) {
found = j;
break;
}
}
if (found != -1) {
count[found]++;
} else {
strcpy(unique[uniqueCount], products[i]);
count[uniqueCount] = 1;
uniqueCount++;
}
}
// Step 2: Find max frequency
int max = 0;
for (int i = 0; i < uniqueCount; i++) {
if (count[i] > max) {
max = count[i];
}
}
// Step 3: Store max frequency products
char result[MAX][LEN];
int resCount = 0;
for (int i = 0; i < uniqueCount; i++) {
if (count[i] == max) {
strcpy(result[resCount], unique[i]);
resCount++;
}
}
// Step 4: Sort alphabetically
for (int i = 0; i < resCount - 1; i++) {
for (int j = i + 1; j < resCount; j++) {
if (strcmp(result[i], result[j]) > 0) {
char temp[LEN];
strcpy(temp, result[i]);
strcpy(result[i], result[j]);
strcpy(result[j], temp);
}
}
}
// Step 5: Print last product
printf("%s\n", result[resCount - 1]);
return 0;
}
0 Comments