Maximum length of same indexed subarrays from two given arrays satisfying the given condition | Function to find maximum length of subarray such that sum of maximum element in subarray in brr [ ] and sum of subarray in arr [ ] * K is at most C ; Base Case ; Let maximum length be 0 ; Perform Binary search ; Find mid value ; Check if the current mid satisfy the given condition ; If yes , then store length ; Otherwise ; Return maximum length stored ; Function to check if it is possible to have such a subarray of length K ; Finds the maximum element in each window of size k ; Check for window of size K ; For all possible subarrays of length k ; Until deque is empty ; Calculate the total cost and check if less than equal to c ; Find sum of current subarray and the total cost ; Include the new element of current subarray ; Discard the element of last subarray ; Remove all the elements in the old window ; Calculate total cost and check <= c ; If current subarray length satisfies ; If it is not possible ;
function maxLength ( a , b , n , c ) { if ( n == 0 ) return 0 ; let max_length = 0 ; let low = 0 , high = n ; while ( low <= high ) { let mid = low + parseInt ( ( high - low ) / 2 , 10 ) ; if ( possible ( a , b , n , c , mid ) ) { max_length = mid ; low = mid + 1 ; } else high = mid - 1 ; } return max_length ; } function possible ( a , b , n , c , k ) { let dq = [ ] ; let sum = 0 ; for ( let i = 0 ; i < k ; i ++ ) { sum += a [ i ] ; while ( dq . length > 0 && b [ i ] > b [ dq [ dq . length - 1 ] ] ) dq . pop ( ) ; dq . push ( i ) ; } let total_cost = sum * k + b [ dq [ 0 ] ] ; if ( total_cost <= c ) return true ; for ( let i = k ; i < n ; i ++ ) { sum += a [ i ] ; sum -= a [ i - k ] ; while ( dq . length > 0 && dq [ 0 ] <= i - k ) dq . pop ( ) ; while ( dq . length > 0 && b [ i ] > b [ dq [ dq . length - 1 ] ] ) dq . pop ( ) ; dq . push ( i ) ; total_cost = sum * k + b [ dq [ 0 ] ] ; if ( total_cost <= c ) return true ; } return false ; } let A = [ 1 , 2 , 1 , 6 , 5 , 5 , 6 , 1 ] ; let B = [ 14 , 8 , 15 , 15 , 9 , 10 , 7 , 12 ] ; let N = A . length ; let C = 40 ; document . write ( maxLength ( A , B , N , C ) ) ;