Minimum time remaining for safety alarm to start | C ++ program for the above approach ; Function to check if the value of mid as the minimum number of hours satisfies the condition ; Stores the sum of speed ; Iterate over the range [ 0 , N ] ; Find the value of speed ; If the bike is considered to be fast add it in sum ; Return the resultant sum ; Function to find the minimum number of time required ; Stores the range of Binary Search ; Stores the minimum number of time required ; Find the value of mid ; If the mid is the resultant speed required ; Update the ans and high ; Otherwise ; Return the minimum number of hours ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; long check ( long H [ ] , long A [ ] , long mid , long N , long M , long L ) { long sum = 0 ; for ( long i = 0 ; i < N ; i ++ ) { long speed = mid * A [ i ] + H [ i ] ; if ( speed >= L ) { sum += speed ; } } return sum ; } long buzzTime ( long N , long M , long L , long H [ ] , long A [ ] ) { long low = 0 , high = 1e10 ; long ans = 0 ; while ( high >= low ) { long mid = low + ( high - low ) / 2 ; if ( check ( H , A , mid , N , M , L ) >= M ) { ans = mid ; high = mid - 1 ; } else low = mid + 1 ; } return ans ; } int main ( ) { long M = 400 , L = 120 ; long H [ ] = { 20 , 50 , 20 } ; long A [ ] = { 20 , 70 , 90 } ; long N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << buzzTime ( N , M , L , H , A ) ; return 0 ; }