C++ code to find maximum score we can assign to first student

C++Server Side ProgrammingProgramming

Suppose we have an array A with n elements and a number m. There are n students giving an exam. The highest possible score is m. A[i] is the score of ith student. We can manipulate each students score, but the conditions must be satisfied. The score will not exceed m, all scores are integers and the average marks of all student does not change. If we want to maximize the first person's score what will be the highest possible score we can give.

So, if the input is like A = [1, 2, 3, 4]; m = 10, then the output will be 10, because the average is 2.5, we can set the scores [10, 0, 0, 0] where the average is same but first one's score is maximum.

Steps

To solve this, we will follow these steps −

sum := 0
n := size of A
for initialize j := 0, when j < n, update (increase j by 1), do:
   sum := sum + A[j]
return minimum of m and sum

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<int> A, int m){
   int sum = 0;
   int n = A.size();
   for (int j = 0; j < n; j++){
      sum += A[j];
   }
   return min(m, sum);
}
int main(){
   vector<int> A = { 1, 2, 3, 4 };
   int m = 10;
   cout << solve(A, m) << endl;
}

Input

{ 1, 2, 3, 4 }, 10

Output

10
raja
Updated on 11-Mar-2022 06:52:42

Advertisements