Minimum value of X such that sum of arr [ i ] | C ++ program for the above approach ; Function to check if there exists an X that satisfies the given conditions ; Find the required value of the given expression ; Function to find the minimum value of X using binary search . ; Boundaries of the Binary Search ; Find the middle value ; Check for the middle value ; Update the upper ; Update the lower ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int a [ ] , int b [ ] , int k , int n , int x ) { int sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { sum = sum + pow ( max ( a [ i ] - x , 0 ) , b [ i ] ) ; } if ( sum <= k ) return true ; else return false ; } int findMin ( int a [ ] , int b [ ] , int n , int k ) { int l = 0 , u = * max_element ( a , a + n ) ; while ( l < u ) { int m = ( l + u ) / 2 ; if ( check ( a , b , k , n , m ) ) { u = m ; } else { l = m + 1 ; } } return l ; } int main ( ) { int arr [ ] = { 2 , 1 , 4 , 3 , 5 } ; int brr [ ] = { 4 , 3 , 2 , 3 , 1 } ; int K = 12 ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << findMin ( arr , brr , N , K ) ; return 0 ; }