Advertisement
Programmin-in-Python

C Program for "Minimum no. of Candies" Problem

Jan 19th, 2022
734
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.40 KB | None | 0 0
  1. /*
  2. Problem :-
  3. ----------
  4.  
  5. There are N children standing in a line. Each child is assigned a rating value. You are giving candies to these children subjected to the following requirements:
  6.  
  7. 1. Each child must have at least one candy.
  8. 2. Children with a higher rating get more candies than their neighbors.
  9.  
  10. What are the minimum candies you must give?
  11.  
  12. Test Case 1 :-
  13.  
  14. Input: [1, 2, 3, 4, 5]
  15. Output: 15
  16.  
  17. Explanation : 1 + 2 + 3 + 4 + 5
  18.  
  19. Test Case 2:
  20.  
  21. Input: [3, 5, 9]
  22. Output: 6
  23.  
  24. Explanation : 1 + 2 + 3
  25.  
  26. Test Case 3:
  27.  
  28. Input: [8, 5, 7, 1, 1]
  29. Output: 11
  30.  
  31. Explanation : 4 + 2 + 3 + 1 + 1
  32. */
  33.  
  34. #include <stdio.h>
  35. void sort(int arr[], int n){
  36.     int temp;
  37.  
  38.     for(int i=0; i<n; i++){
  39.         for(int j=i+1; j<n; j++){
  40.             if(arr[i]>arr[j]){
  41.                 temp = arr[i];
  42.                 arr[i] = arr[j];
  43.                 arr[j] = temp;
  44.             }
  45.         }
  46.     }
  47. }
  48.  
  49. int count(int arr[], int n, int val){
  50.     int count=0;
  51.  
  52.     for(int i=0; i<n; i++){
  53.         if(arr[i]==val){count++;}
  54.     }
  55.     return count;
  56. }
  57.  
  58. int main(){
  59.     int lst[]={1,2,3,4,5}, n=5;
  60.     int candies=0,i=0,candy=1, countval;
  61.     sort(lst, n);
  62.  
  63.     while(i<n){
  64.         countval = count(lst, n, lst[i]);
  65.         if(countval>=2){candies += (countval*candy);}
  66.         else{candies += candy;}
  67.  
  68.         i += countval;
  69.         candy++;
  70.     }
  71.     printf("%d", candies);
  72.     return 0;
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement