
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Code to Find Minimum K to Get More Votes from Students
Suppose we have an array A with n elements. There are n students in a school and each of them has exactly k votes and all votes should be used. There are two parties. The A[i] represents ith student has given A[i] amount of votes to first party and this implies the second party will get k- A[i] number of votes. The second party wants to set k in such a way that they win. What will be the minimum possible value of k.
So, if the input is like A = [2, 2, 3, 2, 2], then the output will be 5, because first party is getting 2 + 2 + 3 + 2 + 2 = 11 votes. if k = 5, then second party will get 3 + 3 + 2 + 3 + 3 = 14 votes and win the election.
Steps
To solve this, we will follow these steps −
n := size of A for initialize k := 0, when k < n, update (increase k by 1), do: x := A[k] m := maximum of m and x s := s + x return maximum of m and (2 * s / n + 1)
Example
Let us see the following implementation to get better understanding −
#include <bits/stdc++.h> using namespace std; int solve(vector<int> A){ int n = A.size(), k = 0, s = 0, m = 0; for (int k = 0; k < n; k++){ int x = A[k]; m = max(m, x); s += x; } return max(m, 2 * s / n + 1); } int main(){ vector<int> A = { 2, 2, 3, 2, 2 }; cout << solve(A) << endl; }
Input
{ 2, 2, 3, 2, 2 }
Output
5