// C++ program for find minimum
// sum of changes in an array
#include <bits/stdc++.h>
using namespace std;
// function to check if the candidate sum
// satisfies the condition of the problem
bool isValid(int candidate, int pre[], int n, int A[],
int p, int q)
{
// flag variable to check wrong answer
bool flag = true;
for (int i = 1; i < n; i++) {
// Now for each element, we are checking
// if its ratio with sum of all previous
// elements + candidate is greater than p/q.
// If so, we will return false.
int curr_sum = pre[i - 1] + candidate;
if (A[i] * q > p * curr_sum) {
flag = false;
break;
}
// comparing like A[i]/(curr_sum)>p/q
// will be error prone.
}
return flag;
}
int solve(int n, int A[], int p, int q)
{
// declaring and constructing
// prefix sum array
int pre[n];
pre[0] = A[0];
for (int i = 1; i < n; i++) {
pre[i] = A[i] + pre[i - 1];
}
// setting lower and upper bound for
// binary search
int lo = 0, hi = INT_MAX, ans = INT_MAX;
// since minimum answer is needed,
// so it is initialized with INT_MAX
while (lo <= hi) {
// calculating mid by using (lo+hi)/2
// may overflow in certain cases
int mid = lo + (hi - lo) / 2;
// checking if required ratio would be
// achieved by all elements if "mid" is
// considered as answer
if (isValid(mid, pre, n, A, p, q)) {
ans = mid;
hi = mid - 1;
}
else {
lo = mid + 1;
}
}
return ans;
}
// Driver Function
int main()
{
int n, p, q;
n = 4, p = 1, q = 100;
int A[] = { 20100, 1, 202, 202 };
// printing the required answer
cout << solve(n, A, p, q) << endl;
}