
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
Find Minimum Value to Assign All Array Elements for Greater Product in C++
Suppose we have an array of n elements. Update all elements of the given array to some min value x, such that arr[i] = x. Such that product of all elements in the new array is strictly greater than the product of all elements of the initial array, where i <= arr[i] <= 10^10, and 1 <= n <= 10^5. So if the array is like [4, 2, 1, 10, 6]. So 4 is the smallest element. 4 * 4 * 4 * 4 * 4 > 4 * 2 * 1 * 10 * 6
As we know that the product of n elements is P. If we have to find nth root of P, to find the nth root of product, we simply divide n from sum of log of n elements of the array and then the ceiling of antilog will be the result.
res = ceil(antilog(log(x) / 10))
or res = ceil(10 ^ (log(x) / 10))
Example
#include <iostream> #include <cmath> #define EPS 1e-15 using namespace std; long long findMinValue(long long arr[], long long n) { long double sum = 0; for (int i=0; i<n; i++) sum += (long double)log10(arr[i])+EPS; long double xl = (long double)(sum/n+EPS); long double res = pow((long double)10.0, (long double)xl) + EPS; return (long long)ceil(res+EPS); } int main() { long long arr[] = {4, 2, 1, 10, 6}; long long n = sizeof(arr)/sizeof(arr[0]); cout << "Min value is: "<< findMinValue(arr, n); }
Output
Min value is: 4
Advertisements