"Maximum path sum for each position with jumps under divisibility condition | PHP program to print maximum path sum ending with each position x such that all path step positions divide x . ; Create an array such that dp [ i ] stores maximum path sum ending with i . ; Calculating maximum sum path for each element . ; Finding previous step for arr [ i ] Moving from 1 to sqrt ( i + 1 ) since all the divisors are present from sqrt ( i + 1 ) . ; Checking if j is divisor of i + 1. ; Checking which divisor will provide greater value . ; Printing the answer ( Maximum path sum ending with every position i + 1. ; Driven Program ; Function calling"
Solution in php:


"Maximum path sum in a triangle . | Function for finding maximum sum ; loop for bottom - up calculation ; for each element , check both elements just below the number and below right to the number add the maximum of them to it ; return the top element which stores the maximum sum ; Driver Code"
Solution in php:


"Maximum path sum in an Inverted triangle | SET 2 | PHP program implementation of Max sum problem in a triangle ; Function for finding maximum sum ; Loop for bottom - up calculation ; For each element , check both elements just below the number and below left to the number add the maximum of them to it ; Return the maximum sum ; Driver Code"
Solution in php:


"Maximum path sum that starting with any cell of 0 | PHP program to find Maximum path sum start any column in row '0' and ends up to any column in row ' n - 1' ; function find maximum sum path ; create 2D matrix to store the sum of the path ; copy all element of first column into ' dp ' first column ; Find maximum path sum that end ups at any column of last row ' N - 1' ; return maximum sum path ; Driver Code"
Solution in php:


"Maximum points of intersection n lines | nC2 = ( n ) * ( n - 1 ) / 2 ; ; n is number of line"
Solution in php:

 < ? php function countMaxIntersect ( $ n ) { return ( $ n ) * ( $ n - 1 ) / 2 ; } $ n = 8 ; echo countMaxIntersect ( $ n ) . "
 " ; ? >


"Maximum positive integer divisible by C and is in the range [ A , B ] | Function to return the required number ; If b % c = 0 then b is the required number ; Else get the maximum multiple of c smaller than b ; Driver code"
Solution in php:

< ? php function getMaxNum ( $ a , $ b , $ c ) { if ( $ b % $ c == 0 ) return $ b ; $ x = ( ( int ) ( $ b / $ c ) * $ c ) ; if ( $ x >= $ a && $ x <= $ b ) return $ x ; else return -1 ; } $ a = 2 ; $ b = 10 ; $ c = 3 ; echo ( getMaxNum ( $ a , $ b , $ c ) ) ; ? >


"Maximum possible difference of two subsets of an array | function for maximum subset diff ; if frequency of any element is two make both equal to zero ; Driver Code"
Solution in php:

< ? php function maxDiff ( $ arr , $ n ) { $ SubsetSum_1 = 0 ; $ SubsetSum_2 = 0 ; for ( $ i = 0 ; $ i <= $ n - 1 ; $ i ++ ) { $ isSingleOccurance = true ; for ( $ j = $ i + 1 ; $ j <= $ n - 1 ; $ j ++ ) { if ( $ arr [ $ i ] == $ arr [ $ j ] ) { $ isSingleOccurance = false ; $ arr [ $ i ] = $ arr [ $ j ] = 0 ; break ; } } if ( $ isSingleOccurance ) { if ( $ arr [ $ i ] > 0 ) $ SubsetSum_1 += $ arr [ $ i ] ; else $ SubsetSum_2 += $ arr [ $ i ] ; } } return abs ( $ SubsetSum_1 - $ SubsetSum_2 ) ; } $ arr = array ( 4 , 2 , -3 , 3 , -2 , -2 , 8 ) ; $ n = sizeof ( $ arr ) ; echo " Maximum ▁ Difference ▁ = ▁ " , maxDiff ( $ arr , $ n ) ; ? >


"Maximum possible difference of two subsets of an array | function for maximum subset diff ; sort the array ; calculate the result ; check for last element ; return result ; Driver Code"
Solution in php:

< ? php function maxDiff ( $ arr , $ n ) { $ result = 0 ; sort ( $ arr ) ; for ( $ i = 0 ; $ i < $ n - 1 ; $ i ++ ) { if ( $ arr [ $ i ] != $ arr [ $ i + 1 ] ) $ result += abs ( $ arr [ $ i ] ) ; else $ i ++ ; } if ( $ arr [ $ n - 2 ] != $ arr [ $ n - 1 ] ) $ result += abs ( $ arr [ $ n - 1 ] ) ; return $ result ; } $ arr = array ( 4 , 2 , -3 , 3 , -2 , -2 , 8 ) ; $ n = count ( $ arr ) ; echo " Maximum ▁ Difference ▁ = ▁ " , maxDiff ( $ arr , $ n ) ; ? >


"Maximum possible intersection by moving centers of line segments | Function to print the maximum intersection ; Case 1 ; Case 2 ; Case 3 ; Driver Code"
Solution in php:

< ? php function max_intersection ( $ center , $ length , $ k ) { sort ( $ center ) ; if ( $ center [ 2 ] - $ center [ 0 ] >= 2 * $ k + $ length ) { return 0 ; } else if ( $ center [ 2 ] - $ center [ 0 ] >= 2 * $ k ) { return ( 2 * $ k - ( $ center [ 2 ] - $ center [ 0 ] - $ length ) ) ; } else return $ length ; } $ center = array ( 1 , 2 , 3 ) ; $ L = 1 ; $ K = 1 ; echo max_intersection ( $ center , $ L , $ K ) ; ? >


"Maximum power of jump required to reach the end of string | Function to calculate the maximum power of the jump ; Initialize the count with 1 ; Find the character at last index ; Start traversing the string ; Check if the current char is equal to the last character ; max_so_far stores maximum value of the power of the jump from starting to ith position ; Reset the count to 1 ; Else , increment the number of jumps / count ; Return the maximum number of jumps ; Driver code"
Solution in php:

< ? php function powerOfJump ( $ s ) { $ count = 1 ; $ max_so_far = PHP_INT_MIN ; $ ch = $ s [ strlen ( $ s ) - 1 ] ; for ( $ i = 0 ; $ i < strlen ( $ s ) ; $ i ++ ) { if ( $ s [ $ i ] == $ ch ) { if ( $ count > $ max_so_far ) { $ max_so_far = $ count ; } $ count = 1 ; } else $ count ++ ; } return $ max_so_far ; } $ st = "1010101" ; echo powerOfJump ( $ st ) ; ? >


"Maximum product of 4 adjacent elements in matrix | PHP program to find out the maximum product in the matrix which four elements are adjacent to each other in one direction ; function to find max product ; iterate the rows . ; iterate the columns . ; check the maximum product in horizontal row . ; check the maximum product in vertical row . ; check the maximum product in diagonal going through down - right ; check the maximum product in diagonal going through up - right ; Driver Code"
Solution in php:


"Maximum product of a triplet ( subsequence of size 3 ) in array | Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; Construct four auxiliary vectors of size n and initialize them by - 1 ; will contain max product ; to store maximum element on left of array ; to store minimum element on left of array ; leftMax [ i ] will contain max element on left of arr [ i ] excluding arr [ i ] . leftMin [ i ] will contain min element on left of arr [ i ] excluding arr [ i ] . ; reset max_sum to store maximum element on right of array ; reset min_sum to store minimum element on right of array ; rightMax [ i ] will contain max element on right of arr [ i ] excluding arr [ i ] . rightMin [ i ] will contain min element on right of arr [ i ] excluding arr [ i ] . ; For all array indexes i except first and last , compute maximum of arr [ i ] * x * y where x can be leftMax [ i ] or leftMin [ i ] and y can be rightMax [ i ] or rightMin [ i ] . ; Driver program to test above functions"
Solution in php:

< ? php function maxProduct ( $ arr , $ n ) { if ( $ n < 3 ) return -1 ; $ leftMin = array_fill ( 0 , $ n , -1 ) ; $ rightMin = array_fill ( 0 , $ n , -1 ) ; $ leftMax = array_fill ( 0 , $ n , -1 ) ; $ rightMax = array_fill ( 0 , $ n , -1 ) ; $ max_product = PHP_INT_MIN ; $ max_sum = $ arr [ 0 ] ; $ min_sum = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ leftMax [ $ i ] = $ max_sum ; if ( $ arr [ $ i ] > $ max_sum ) $ max_sum = $ arr [ $ i ] ; $ leftMin [ $ i ] = $ min_sum ; if ( $ arr [ $ i ] < $ min_sum ) $ min_sum = $ arr [ $ i ] ; } $ max_sum = $ arr [ $ n - 1 ] ; $ min_sum = $ arr [ $ n - 1 ] ; for ( $ j = $ n - 2 ; $ j >= 0 ; $ j -- ) { $ rightMax [ $ j ] = $ max_sum ; if ( $ arr [ $ j ] > $ max_sum ) $ max_sum = $ arr [ $ j ] ; $ rightMin [ $ j ] = $ min_sum ; if ( $ arr [ $ j ] < $ min_sum ) $ min_sum = $ arr [ $ j ] ; } for ( $ i = 1 ; $ i < $ n - 1 ; $ i ++ ) { $ max1 = max ( $ arr [ $ i ] * $ leftMax [ $ i ] * $ rightMax [ $ i ] , $ arr [ $ i ] * $ leftMin [ $ i ] * $ rightMin [ $ i ] ) ; $ max2 = max ( $ arr [ $ i ] * $ leftMax [ $ i ] * $ rightMin [ $ i ] , $ arr [ $ i ] * $ leftMin [ $ i ] * $ rightMax [ $ i ] ) ; $ max_product = max ( $ max_product , max ( $ max1 , $ max2 ) ) ; } return $ max_product ; } $ arr = array ( 1 , 4 , 3 , -6 , -7 , 0 ) ; $ n = count ( $ arr ) ; $ max = maxProduct ( $ arr , $ n ) ; if ( $ max == -1 ) echo " No ▁ Triplet ▁ Exists " ; else echo " Maximum ▁ product ▁ is ▁ " . $ max ; ? >


"Maximum product of a triplet ( subsequence of size 3 ) in array | Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; Sort the array in ascending order ; Return the maximum of product of last three elements and product of first two elements and last element ; Driver code"
Solution in php:

< ? php function maxProduct ( $ arr , $ n ) { if ( $ n < 3 ) { return -1 ; } sort ( $ arr ) ; return max ( $ arr [ 0 ] * $ arr [ 1 ] * $ arr [ $ n - 1 ] , $ arr [ $ n - 1 ] * $ arr [ $ n - 2 ] * $ arr [ $ n - 3 ] ) ; } $ arr = array ( -10 , -3 , 5 , 6 , -20 ) ; $ n = sizeof ( $ arr ) ; $ max = maxProduct ( $ arr , $ n ) ; if ( $ max == -1 ) { echo ( " No ▁ Triplet ▁ Exists " ) ; } else { echo ( " Maximum ▁ product ▁ is ▁ " . $ max ) ; }


"Maximum product of a triplet ( subsequence of size 3 ) in array | Function to find a maximum product of a triplet in array of integers of size n ; if size is less than 3 , no triplet exists ; will contain max product ; Driver Code"
Solution in php:

< ? php function maxProduct ( $ arr , $ n ) { $ INT_MIN = 0 ; if ( $ n < 3 ) return -1 ; $ max_product = $ INT_MIN ; for ( $ i = 0 ; $ i < $ n - 2 ; $ i ++ ) for ( $ j = $ i + 1 ; $ j < $ n - 1 ; $ j ++ ) for ( $ k = $ j + 1 ; $ k < $ n ; $ k ++ ) $ max_product = max ( $ max_product , $ arr [ $ i ] * $ arr [ $ j ] * $ arr [ $ k ] ) ; return $ max_product ; } $ arr = array ( 10 , 3 , 5 , 6 , 20 ) ; $ n = sizeof ( $ arr ) ; $ max = maxProduct ( $ arr , $ n ) ; if ( $ max == -1 ) echo " No ▁ Triplet ▁ Exists " ; else echo " Maximum ▁ product ▁ is ▁ " , $ max ; ? >


"Maximum product of an increasing subsequence | Returns product of maximum product increasing subsequence . ; Initialize MPIS values ; Compute optimized MPIS values considering every element as ending element of sequence ; Pick maximum of all product values ; Driver program to test above function"
Solution in php:

< ? php function lis ( & $ arr , $ n ) { $ mpis = array_fill ( 0 , $ n , NULL ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ mpis [ $ i ] = $ arr [ $ i ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) for ( $ j = 0 ; $ j < $ i ; $ j ++ ) if ( $ arr [ $ i ] > $ arr [ $ j ] && $ mpis [ $ i ] < ( $ mpis [ $ j ] * $ arr [ $ i ] ) ) $ mpis [ $ i ] = $ mpis [ $ j ] * $ arr [ $ i ] ; return max ( $ mpis ) ; } $ arr = array ( 3 , 100 , 4 , 5 , 150 , 6 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo lis ( $ arr , $ n ) ; return 0 ; ? >


"Maximum product of subsequence of size k | Required function ; sorting given input array ; variable to store final product of all element of sub - sequence of size k ; CASE I If max element is 0 and k is odd then max product will be 0 ; CASE II If all elements are negative and k is odd then max product will be product of rightmost - subarray of size k ; else i is current left pointer index ; j is current right pointer index ; CASE III if k is odd and rightmost element in sorted array is positive then it must come in subsequence Multiplying A [ j ] with product and correspondingly changing j ; CASE IV Now k is even Now we deal with pairs Each time a pair is multiplied to product ie . . two elements are added to subsequence each time Effectively k becomes half Hence , k >>= 1 means k /= 2 ; Now finding k corresponding pairs to get maximum possible value of product ; product from left pointers ; product from right pointers ; Taking the max product from two choices Correspondingly changing the pointer 's position ; Finally return product ; Driver Code"
Solution in php:

< ? php function maxProductSubarrayOfSizeK ( $ A , $ n , $ k ) { sort ( $ A ) ; $ product = 1 ; if ( $ A [ $ n - 1 ] == 0 && ( $ k & 1 ) ) return 0 ; if ( $ A [ $ n - 1 ] <= 0 && ( $ k & 1 ) ) { for ( $ i = $ n - 1 ; $ i >= $ n - $ k ; $ i -- ) $ product *= $ A [ $ i ] ; return $ product ; } $ i = 0 ; $ j = $ n - 1 ; if ( $ k & 1 ) { $ product *= $ A [ $ j ] ; $ j -- ; $ k -- ; } $ k >>= 1 ; for ( $ itr = 0 ; $ itr < $ k ; $ itr ++ ) { $ left_product = $ A [ $ i ] * $ A [ $ i + 1 ] ; $ right_product = $ A [ $ j ] * $ A [ $ j - 1 ] ; if ( $ left_product > $ right_product ) { $ product *= $ left_product ; $ i += 2 ; } else { $ product *= $ right_product ; $ j -= 2 ; } } return $ product ; } $ A = array ( 1 , 2 , -1 , -3 , -6 , 4 ) ; $ n = count ( $ A ) ; $ k = 4 ; echo maxProductSubarrayOfSizeK ( $ A , $ n , $ k ) ; ? >


"Maximum product quadruple ( sub | Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; Initialize Maximum , second maximum , third maximum and fourth maximum element ; Initialize Minimum , second minimum , third minimum and fourth minimum element ; Update Maximum , second maximum , third maximum and fourth maximum element ; Update second maximum , third maximum and fourth maximum element ; Update third maximum and fourth maximum element ; Update fourth maximum element ; Update Minimum , second minimum , third minimum and fourth minimum element ; Update second minimum , third minimum and fourth minimum element ; Update third minimum and fourth minimum element ; Update fourth minimum element ; Return the maximum of x , y and z ; Driver Code"
Solution in php:

< ? php function maxProduct ( $ arr , $ n ) { if ( $ n < 4 ) return -1 ; $ maxA = -2147483648 ; $ maxB = -2147483648 ; $ maxC = -2147483648 ; $ maxD = -2147483648 ; $ minA = 2147483647 ; $ minB = 2147483647 ; $ minC = 2147483647 ; $ minD = 2147483647 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] > $ maxA ) { $ maxD = $ maxC ; $ maxC = $ maxB ; $ maxB = $ maxA ; $ maxA = $ arr [ $ i ] ; } elseif ( $ arr [ $ i ] > $ maxB ) { $ maxD = $ maxC ; $ maxC = $ maxB ; $ maxB = $ arr [ $ i ] ; } elseif ( $ arr [ $ i ] > $ maxC ) { $ maxD = $ maxC ; $ maxC = $ arr [ $ i ] ; } elseif ( $ arr [ $ i ] > $ maxD ) $ maxD = $ arr [ $ i ] ; if ( $ arr [ $ i ] < $ minA ) { $ minD = $ minC ; $ minC = $ minB ; $ minB = $ minA ; $ minA = $ arr [ $ i ] ; } elseif ( $ arr [ $ i ] < $ minB ) { $ minD = $ minC ; $ minC = $ minB ; $ minB = $ arr [ $ i ] ; } elseif ( $ arr [ $ i ] < $ minC ) { $ minD = $ minC ; $ minC = $ arr [ $ i ] ; } elseif ( $ arr [ $ i ] < $ minD ) $ minD = $ arr [ $ i ] ; } $ x = $ maxA * $ maxB * $ maxC * $ maxD ; $ y = $ minA * $ minB * $ minC * $ minD ; $ z = $ minA * $ minB * $ maxA * $ maxB ; return max ( $ x , max ( $ y , $ z ) ) ; } $ arr = array ( 1 , -4 , 3 , -6 , 7 , 0 ) ; $ n = count ( $ arr ) ; $ max = maxProduct ( $ arr , $ n ) ; if ( $ max == -1 ) echo " No ▁ Quadruple ▁ Exists " ; else echo " Maximum ▁ product ▁ is ▁ " . $ max ; ? >


"Maximum product quadruple ( sub | Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; Sort the array in ascending order ; Return the maximum of x , y and z ; Driver Code"
Solution in php:

< ? php function maxProduct ( $ arr , $ n ) { if ( $ n < 4 ) return -1 ; sort ( $ arr ) ; $ x = $ arr [ $ n - 1 ] * $ arr [ $ n - 2 ] * $ arr [ $ n - 3 ] * $ arr [ $ n - 4 ] ; $ y = $ arr [ 0 ] * $ arr [ 1 ] * $ arr [ 2 ] * $ arr [ 3 ] ; $ z = $ arr [ 0 ] * $ arr [ 1 ] * $ arr [ $ n - 1 ] * $ arr [ $ n - 2 ] ; return max ( $ x , max ( $ y , $ z ) ) ; } $ arr = array ( -10 , -3 , 5 , 6 , -20 ) ; $ n = sizeof ( $ arr ) ; $ max = maxProduct ( $ arr , $ n ) ; if ( $ max == -1 ) echo " No ▁ Quadruple ▁ Exists " ; else echo " Maximum ▁ product ▁ is ▁ " . $ max ;


"Maximum product quadruple ( sub | Function to find a maximum product of a quadruple in array of integers of size n ; if size is less than 4 , no quadruple exists ; will contain max product ; Driver Code"
Solution in php:

< ? php function maxProduct ( $ arr , $ n ) { if ( $ n < 4 ) return -1 ; $ max_product = PHP_INT_MIN ; for ( $ i = 0 ; $ i < $ n - 3 ; $ i ++ ) for ( $ j = $ i + 1 ; $ j < $ n - 2 ; $ j ++ ) for ( $ k = $ j + 1 ; $ k < $ n - 1 ; $ k ++ ) for ( $ l = $ k + 1 ; $ l < $ n ; $ l ++ ) $ max_product = max ( $ max_product , $ arr [ $ i ] * $ arr [ $ j ] * $ arr [ $ k ] * $ arr [ $ l ] ) ; return $ max_product ; } $ arr = array ( 10 , 3 , 5 , 6 , 20 ) ; $ n = count ( $ arr ) ; $ max = maxProduct ( $ arr , $ n ) ; if ( $ max == -1 ) echo " No ▁ Quadruple ▁ Exists " ; else echo " Maximum ▁ product ▁ is ▁ " , $ max ; ? >


"Maximum product subset of an array | PHP program to find maximum product of a subset . ; Find count of negative numbers , count of zeros , negative number with least absolute value and product of non - zero numbers ; If number is 0 , we don 't  multiply it with product. ; Count negatives and keep track of negative number with least absolute value . ; If there are all zeros ; If there are odd number of negative numbers ; Exceptional case : There is only negative and all other are zeros ; Otherwise result is product of all non - zeros divided by negative number with least absolute value . ; Driver Code"
Solution in php:

< ? php function maxProductSubset ( $ a , $ n ) { if ( $ n == 1 ) return $ a [ 0 ] ; $ max_neg = PHP_INT_MIN ; $ count_neg = 0 ; $ count_zero = 0 ; $ prod = 1 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ a [ $ i ] == 0 ) { $ count_zero ++ ; continue ; } if ( $ a [ $ i ] < 0 ) { $ count_neg ++ ; $ max_neg = max ( $ max_neg , $ a [ $ i ] ) ; } $ prod = $ prod * $ a [ $ i ] ; } if ( $ count_zero == $ n ) return 0 ; if ( $ count_neg & 1 ) { if ( $ count_neg == 1 && $ count_zero > 0 && $ count_zero + $ count_neg == $ n ) return 0 ; $ prod = $ prod / $ max_neg ; } return $ prod ; } $ a = array ( -1 , -1 , -2 , 4 , 3 ) ; $ n = sizeof ( $ a ) ; echo maxProductSubset ( $ a , $ n ) ; ? >


"Maximum profit after buying and selling stocks with transaction fees | PHP implementation of above approach ; b [ 0 ] will contain the maximum profit ; b [ 1 ] will contain the day on which we are getting the maximum profit ; here finding the max profit ; if we get less then or equal to zero it means we are not getting the profit ; check if sum is greater then maximum then store the new maximum ; Driver code"
Solution in php:


"Maximum profit by buying and selling a share at most k times | Function to find out maximum profit by buying & selling a share atmost k times given stock price of n days ; table to store results of subproblems profit [ t ] [ i ] stores maximum profit using atmost t transactions up to day i ( including day i ) ; For day 0 , you can 't  earn money irrespective  of how many times you trade ; profit is 0 if we don 't  do any transaction  (i.e. k =0) ; fill the table in bottom - up fashion ; Driver Code"
Solution in php:

< ? php function maxProfit ( $ price , $ n , $ k ) { $ profit [ $ k + 1 ] [ $ n + 1 ] = 0 ; for ( $ i = 0 ; $ i <= $ k ; $ i ++ ) $ profit [ $ i ] [ 0 ] = 0 ; for ( $ j = 0 ; $ j <= $ n ; $ j ++ ) $ profit [ 0 ] [ $ j ] = 0 ; $ prevDiff = NULL ; for ( $ i = 1 ; $ i <= $ k ; $ i ++ ) { for ( $ j = 1 ; $ j < $ n ; $ j ++ ) { $ prevDiff = max ( $ prevDiff , $ profit [ $ i - 1 ] [ $ j - 1 ] - $ price [ $ j - 1 ] ) ; $ profit [ $ i ] [ $ j ] = max ( $ profit [ $ i ] [ $ j - 1 ] , $ price [ $ j ] + $ prevDiff ) ; } } return $ profit [ $ k ] [ $ n - 1 ] ; } $ k = 3 ; $ price = array ( 12 , 14 , 17 , 10 , 14 , 13 , 12 , 15 ) ; $ n = sizeof ( $ price ) ; echo " Maximum ▁ profit ▁ is : ▁ " , maxProfit ( $ price , $ n , $ k ) ; ? >


"Maximum set bit sum in array without considering adjacent elements | Function to count total number of set bits in an integer ; Maximum sum of set bits ; Calculate total number of set bits for every element of the array ; find total set bits for each number and store back into the array ; current max excluding i ; current max including i ; return max of incl and excl ; Driver code"
Solution in php:

 < ? php function bit ( $ n ) { $ count = 0 ; while ( $ n ) { $ count ++ ; $ n = $ n & ( $ n - 1 ) ; } return $ count ; } function maxSumOfBits ( $ arr , $ n ) { for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ arr [ $ i ] = bit ( $ arr [ $ i ] ) ; } $ incl = $ arr [ 0 ] ; $ excl = 0 ; $ excl_new ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ excl_new = ( $ incl > $ excl ) ? $ incl : $ excl ; $ incl = $ excl + $ arr [ $ i ] ; $ excl = $ excl_new ; } return ( ( $ incl > $ excl ) ? $ incl : $ excl ) ; } $ arr = array ( 1 , 2 , 4 , 5 , 6 , 7 , 20 , 25 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo maxSumOfBits ( $ arr , $ n ) ; #This  Code is Contributed by ajit
? >


"Maximum size of sub | Function that compares a and b ; Function to return length of longest subarray that satisfies one of the given conditions ; Driver Code ; Print the required answer"
Solution in php:

< ? php function cmp ( $ a , $ b ) { return ( $ a > $ b ) - ( $ a < $ b ) ; } function maxSubarraySize ( $ arr ) { $ N = sizeof ( $ arr ) ; $ ans = 1 ; $ anchor = 0 ; for ( $ i = 1 ; $ i < $ N ; $ i ++ ) { $ c = cmp ( $ arr [ $ i - 1 ] , $ arr [ $ i ] ) ; if ( $ c == 0 ) $ anchor = $ i ; else if ( $ i == $ N - 1 or $ c * cmp ( $ arr [ $ i ] , $ arr [ $ i + 1 ] ) != -1 ) { $ ans = max ( $ ans , $ i - $ anchor + 1 ) ; $ anchor = $ i ; } } return $ ans ; } $ arr = array ( 9 , 4 , 2 , 10 , 7 , 8 , 8 , 1 , 9 ) ; echo maxSubarraySize ( $ arr ) ; ? >


"Maximum steps to transform 0 to X with bitwise AND | Function to get no of set bits in binary representation of positive integer n ; Driver code"
Solution in php:

< ? php function countSetBits ( $ n ) { $ count = 0 ; while ( $ n ) { $ count += $ n & 1 ; $ n >>= 1 ; } return $ count ; } $ i = 3 ; echo ( countSetBits ( $ i ) ) ; ? >


"Maximum students to pass after giving bonus to everybody and not exceeding 100 marks | Function to return the number of students that can pass ; maximum marks ; maximum bonus marks that can be given ; counting the number of students that can pass ; Driver code"
Solution in php:

< ? php function check ( $ n , $ marks ) { $ x = max ( $ marks ) ; $ bonus = 100 - $ x ; $ c = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ marks [ $ i ] + $ bonus >= 50 ) $ c += 1 ; } return $ c ; } $ n = 5 ; $ marks = array ( 0 , 21 , 83 , 45 , 64 ) ; echo check ( $ n , $ marks ) ;


"Maximum subarray sum in O ( n ) using prefix sum | Function to compute maximum subarray sum in linear time . ; Initialize minimum prefix sum to 0. ; Initialize maximum subarray sum so far to - infinity . ; Initialize and compute the prefix sum array . ; loop through the array , keep track of minimum prefix sum so far and maximum subarray sum . ; Test case 1 ; Test case 2"
Solution in php:

< ? php function maximumSumSubarray ( $ arr , $ n ) { $ min_prefix_sum = 0 ; $ res = PHP_INT_MIN ; $ prefix_sum = array ( ) ; $ prefix_sum [ 0 ] = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) $ prefix_sum [ $ i ] = $ prefix_sum [ $ i - 1 ] + $ arr [ $ i ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ res = max ( $ res , $ prefix_sum [ $ i ] - $ min_prefix_sum ) ; $ min_prefix_sum = min ( $ min_prefix_sum , $ prefix_sum [ $ i ] ) ; } return $ res ; } $ arr1 = array ( -2 , -3 , 4 , -1 , -2 , 1 , 5 , -3 ) ; $ n1 = count ( $ arr1 ) ; echo maximumSumSubarray ( $ arr1 , $ n1 ) , " " ; $ arr2 = array ( 4 , -8 , 9 , -4 , 1 , -8 , -1 , 6 ) ; $ n2 = count ( $ arr2 ) ; echo maximumSumSubarray ( $ arr2 , $ n2 ) ; ? >


"Maximum subsequence sum such that no three are consecutive | PHP program to find the maximum sum such that no three are consecutive using recursion . ; Returns maximum subsequence sum such that no three elements are consecutive ; Base cases ( process first three elements ) ; Process rest of the elements We have three cases ; Driver code"
Solution in php:

< ? php $ arr = array ( 100 , 1000 , 100 , 1000 , 1 ) ; $ sum = array_fill ( 0 , count ( $ arr ) + 1 , -1 ) ; function maxSumWO3Consec ( $ n ) { global $ sum , $ arr ; if ( $ sum [ $ n ] != -1 ) return $ sum [ $ n ] ; if ( $ n == 0 ) return $ sum [ $ n ] = 0 ; if ( $ n == 1 ) return $ sum [ $ n ] = $ arr [ 0 ] ; if ( $ n == 2 ) return $ sum [ $ n ] = $ arr [ 1 ] + $ arr [ 0 ] ; return $ sum [ $ n ] = max ( max ( maxSumWO3Consec ( $ n - 1 ) , maxSumWO3Consec ( $ n - 2 ) + $ arr [ $ n ] ) , $ arr [ $ n ] + $ arr [ $ n - 1 ] + maxSumWO3Consec ( $ n - 3 ) ) ; } $ n = count ( $ arr ) ; echo maxSumWO3Consec ( $ n ) ; ? >


"Maximum subsequence sum such that no three are consecutive | Returns maximum subsequence sum such that no three elements are consecutive ; Stores result for subarray arr [ 0. . i ] , i . e . , maximum possible sum in subarray arr [ 0. . i ] such that no three elements are consecutive$ . ; Base cases ( process first three elements ) ; Process rest of the elements We have three cases 1 ) Exclude arr [ i ] , i . e . , sum [ i ] = sum [ i - 1 ] 2 ) Exclude arr [ i - 1 ] , i . e . , sum [ i ] = sum [ i - 2 ] + arr [ i ] 3 ) Exclude arr [ i - 2 ] , i . e . , sum [ i - 3 ] + arr [ i ] + arr [ i - 1 ] ; Driver code"
Solution in php:


"Maximum subset with bitwise OR equal to k | function to find the maximum subset with bitwise OR equal to k ; If the bitwise OR of k and element is equal to k , then include that element in the subset ; Store the bitwise OR of elements in v ; If ans is not equal to k , subset doesn 't exist ; Driver Code"
Solution in php:

 < ? php function subsetBitwiseORk ( $ arr , $ n , $ k ) { $ v = array ( ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( ( $ arr [ $ i ] $ k ) == $ k ) array_push ( $ v , $ arr [ $ i ] ) ; } $ ans = 0 ; for ( $ i = 0 ; $ i < count ( $ v ) ; $ i ++ ) $ ans |= $ v [ $ i ] ; if ( $ ans != $ k ) { echo ( " Subset ▁ does ▁ not ▁ exist
 " ) ; return ; } for ( $ i = 0 ; $ i < count ( $ v ) ; $ i ++ ) echo ( $ v [ $ i ] . " ▁ " ) ; } $ k = 3 ; $ arr = array ( 1 , 4 , 2 ) ; $ n = count ( $ arr ) ; subsetBitwiseORk ( $ arr , $ n , $ k ) ; ? >


"Maximum sum after repeatedly dividing N by a divisor | Function to find the smallest divisor ; Function to find the maximum sum ; Driver Code"
Solution in php:

 < ? php function smallestDivisor ( $ n ) { $ mx = sqrt ( $ n ) ; for ( $ i = 2 ; $ i <= $ mx ; $ i ++ ) if ( $ n % $ i == 0 ) return $ i ; return $ n ; } function maxSum ( $ n ) { $ res = $ n ; while ( $ n > 1 ) { $ divi = smallestDivisor ( $ n ) ; $ n /= $ divi ; $ res += $ n ; } return $ res ; } $ n = 34 ; echo maxSum ( $ n ) ; #This  code is contributed by akt_mit.
? >


"Maximum sum alternating subsequence | Return sum of maximum sum alternating sequence starting with arr [ 0 ] and is first decreasing . ; handling the edge case ; stores sum of decreasing and increasing sub - sequence ; store sum of increasing and decreasing sun - sequence ; As per question , first element must be part of solution . ; Traverse remaining elements of array ; IF current sub - sequence is decreasing the update dec [ j ] if needed . dec [ i ] by current inc [ j ] + arr [ i ] ; Revert the flag , if first decreasing is found ; If next element is greater but flag should be 1 i . e . this element should be counted after the first decreasing element gets counted ; If current sub - sequence is increasing then update inc [ i ] ; find maximum sum in b / w inc [ ] and dec [ ] ; return maximum sum alternate sun - sequence ; Driver Code"
Solution in php:

< ? php function maxAlternateSum ( $ arr , $ n ) { if ( $ n == 1 ) return $ arr [ 0 ] ; $ min = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ min = max ( $ min , $ arr [ $ i ] ) ; } if ( $ arr [ 0 ] == $ min ) return $ arr [ 0 ] ; $ dec = array_fill ( 0 , $ n , 0 ) ; $ inc = array_fill ( 0 , $ n , 0 ) ; $ dec [ 0 ] = $ inc [ 0 ] = $ arr [ 0 ] ; $ flag = 0 ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { for ( $ j = 0 ; $ j < $ i ; $ j ++ ) { if ( $ arr [ $ j ] > $ arr [ $ i ] ) { $ dec [ $ i ] = max ( $ dec [ $ i ] , $ inc [ $ j ] + $ arr [ $ i ] ) ; $ flag = 1 ; } else if ( $ arr [ $ j ] < $ arr [ $ i ] && $ flag == 1 ) $ inc [ $ i ] = max ( $ inc [ $ i ] , $ dec [ $ j ] + $ arr [ $ i ] ) ; } } $ result = - ( PHP_INT_MAX - 1 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ result < $ inc [ $ i ] ) $ result = $ inc [ $ i ] ; if ( $ result < $ dec [ $ i ] ) $ result = $ dec [ $ i ] ; } return $ result ; } $ arr = array ( 8 , 2 , 3 , 5 , 7 , 9 , 10 ) ; $ n = sizeof ( $ arr ) ; echo " Maximum ▁ sum ▁ = ▁ " , maxAlternateSum ( $ arr , $ n ) ; ? >


"Maximum sum and product of the M consecutive digits in a number | Function to find the maximum product ; Driver code"
Solution in php:

< ? php function maxProductSum ( $ str , $ m ) { $ n = strlen ( $ str ) ; $ maxProd = PHP_INT_MIN ; $ maxSum = PHP_INT_MIN ; for ( $ i = 0 ; $ i <= ( $ n - $ m ) ; $ i ++ ) { $ product = 1 ; $ sum = 0 ; for ( $ j = $ i ; $ j < ( $ m + $ i ) ; $ j ++ ) { $ product = $ product * ( $ str [ $ j ] - '0' ) ; $ sum = $ sum + ( $ str [ $ j ] - '0' ) ; } $ maxProd = max ( $ maxProd , $ product ) ; $ maxSum = max ( $ maxSum , $ sum ) ; } echo " Maximum ▁ Product ▁ = ▁ " , $ maxProd ; echo " Maximum Sum = " } $ str = "3605356297" ; $ m = 3 ; maxProductSum ( $ str , $ m ) ; ? >


"Maximum sum bitonic subarray | function to find the maximum sum bitonic subarray ; ' msis [ ] ' to store the maximum sum increasing subarray up to each index of ' arr ' from the beginning ' msds [ ] ' to store the maximum sum decreasing subarray from each index of ' arr ' up to the end ; to store the maximum sum bitonic subarray ; building up the maximum sum increasing subarray for each array index ; building up the maximum sum decreasing subarray for each array index ; for each array index , calculating the maximum sum of bitonic subarray of which it is a part of ; if true , then update ' max ' bitonic subarray sum ; required maximum sum ; Driver Code"
Solution in php:

< ? php function maxSumBitonicSubArr ( $ arr , $ n ) { $ msis = array ( ) ; $ msds = array ( ) ; $ max_sum = PHP_INT_MIN ; $ msis [ 0 ] = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] > $ arr [ $ i - 1 ] ) $ msis [ $ i ] = $ msis [ $ i - 1 ] + $ arr [ $ i ] ; else $ msis [ $ i ] = $ arr [ $ i ] ; $ msds [ $ n - 1 ] = $ arr [ $ n - 1 ] ; for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) if ( $ arr [ $ i ] > $ arr [ $ i + 1 ] ) $ msds [ $ i ] = $ msds [ $ i + 1 ] + $ arr [ $ i ] ; else $ msds [ $ i ] = $ arr [ $ i ] ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ max_sum < ( $ msis [ $ i ] + $ msds [ $ i ] - $ arr [ $ i ] ) ) $ max_sum = $ msis [ $ i ] + $ msds [ $ i ] - $ arr [ $ i ] ; return $ max_sum ; } $ arr = array ( 5 , 3 , 9 , 2 , 7 , 6 , 4 ) ; $ n = sizeof ( $ arr ) ; echo " Maximum ▁ Sum ▁ = ▁ " , maxSumBitonicSubArr ( $ arr , $ n ) ; ? >


"Maximum sum by adding numbers with same number of set bits | count the number of bits for each element of array ; Count the number of set bits ; Function to return the the maximum sum ; Calculate the ; Assuming the number to be a maximum of 32 bits ; Add the number to the number of set bits ; Find the maximum sum ; Driver code"
Solution in php:

< ? php function bit_count ( $ n ) { $ count = 0 ; while ( $ n ) { $ count ++ ; $ n = $ n & ( $ n - 1 ) ; } return $ count ; } function maxsum ( $ arr , $ n ) { $ bits = array ( $ n ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ bits [ $ i ] = bit_count ( $ arr [ $ i ] ) ; } $ sum = array_fill ( 0 , 32 , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ sum [ $ bits [ $ i ] ] += $ arr [ $ i ] ; } $ maximum = 0 ; for ( $ i = 0 ; $ i < 32 ; $ i ++ ) { $ maximum = max ( $ sum [ $ i ] , $ maximum ) ; } return $ maximum ; } $ arr = array ( 2 , 3 , 8 , 5 , 6 , 7 ) ; $ n = sizeof ( $ arr ) ; echo maxsum ( $ arr , $ n ) ; ? >


"Maximum sum in a 2 x n grid such that no two elements are adjacent | Function to find max sum without adjacent ; Sum including maximum element of first column ; Not including first column 's element ; Traverse for further elements ; Update max_sum on including or excluding of previous column ; Include current column . Add maximum element from both row of current column ; If current column doesn 't  to be included ; Return maximum of excl and incl As that will be the maximum sum ; Driver code"
Solution in php:

< ? php function maxSum ( $ grid , $ n ) { $ incl = max ( $ grid [ 0 ] [ 0 ] , $ grid [ 1 ] [ 0 ] ) ; $ excl = 0 ; $ excl_new ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ excl_new = max ( $ excl , $ incl ) ; $ incl = $ excl + max ( $ grid [ 0 ] [ $ i ] , $ grid [ 1 ] [ $ i ] ) ; $ excl = $ excl_new ; } return max ( $ excl , $ incl ) ; } $ grid = array ( array ( 1 , 2 , 3 , 4 , 5 ) , array ( 6 , 7 , 8 , 9 , 10 ) ) ; $ n = 5 ; echo maxSum ( $ grid , $ n ) ; ? >


"Maximum sum increasing subsequence from a prefix and a given element after prefix is must | PHP program to find maximum sum increasing subsequence till i - th index and including k - th index . ; Initializing the first row of the dp [ ] [ ] . ; Creating the dp [ ] [ ] matrix . ; To calculate for i = 4 and k = 6. ; Driver Code"
Solution in php:


"Maximum sum of a path in a Right Number Triangle | function to find maximum sum path ; Adding the element of row 1 to both the elements of row 2 to reduce a step from the loop ; Traverse remaining rows ; Loop to traverse columns ; tri [ i ] would store the possible combinations of sum of the paths ; array at n - 1 index ( tri [ i ] ) stores all possible adding combination , finding the maximum one out of them ; Driver Code"
Solution in php:


"Maximum sum of absolute difference of any permutation | PHP implementation of above algorithm ; final sequence stored in the vector ; sort the original array so that we can retrieve the large elements from the end of array elements ; In this loop first we will insert one smallest element not entered till that time in final sequence and then enter a highest element ( not entered till that time ) in final sequence so that we have large difference value . This process is repeated till all array has completely entered in sequence . Here , we have loop till n / 2 because we are inserting two elements at a time in loop . ; If there are odd elements , push the middle element at the end . ; variable to store the maximum sum of absolute difference ; In this loop absolute difference of elements for the final sequence is calculated . ; absolute difference of last element and 1 st element ; return the value ; Driver Code"
Solution in php:

 < ? php function MaxSumDifference ( & $ a , $ n ) { $ finalSequence = array ( ) ; sort ( $ a ) ; for ( $ i = 0 ; $ i < $ n / 2 ; ++ $ i ) { array_push ( $ finalSequence , $ a [ $ i ] ) ; array_push ( $ finalSequence , $ a [ $ n - $ i - 1 ] ) ; } if ( $ n % 2 != 0 ) array_push ( $ finalSequence , $ a [ $ n - 1 ] ) ; $ MaximumSum = 0 ; for ( $ i = 0 ; $ i < $ n - 1 ; ++ $ i ) { $ MaximumSum = $ MaximumSum + abs ( $ finalSequence [ $ i ] - $ finalSequence [ $ i + 1 ] ) ; } $ MaximumSum = $ MaximumSum + abs ( $ finalSequence [ $ n - 1 ] - $ finalSequence [ 0 ] ) ; return $ MaximumSum ; } $ a = array ( 1 , 2 , 4 , 8 ) ; $ n = sizeof ( $ a ) ; echo MaxSumDifference ( $ a , $ n ) . "
 " ; ? >


"Maximum sum of all elements of array after performing given operations | Function to calculate Maximum Subarray Sum or Kadane 's Algorithm ; Function to find the maximum sum after given operations ; To store sum of all elements ; Maximum sum of a subarray ; Calculate the sum of all elements ; Driver Code ; size of an array"
Solution in php:

< ? php function maxSubArraySum ( $ a , $ size ) { $ max_so_far = PHP_INT_MIN ; $ max_ending_here = 0 ; for ( $ i = 0 ; $ i < $ size ; $ i ++ ) { $ max_ending_here = $ max_ending_here + $ a [ $ i ] ; if ( $ max_so_far < $ max_ending_here ) $ max_so_far = $ max_ending_here ; if ( $ max_ending_here < 0 ) $ max_ending_here = 0 ; } return $ max_so_far ; } function maxSum ( $ a , $ n ) { $ S = 0 ; $ S1 = maxSubArraySum ( $ a , $ n ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ S += $ a [ $ i ] ; return ( 2 * $ S1 - $ S ) ; } $ a = array ( -35 , 32 , -24 , 0 , 27 , -10 , 0 , -19 ) ; $ n = sizeof ( $ a ) ; echo ( maxSum ( $ a , $ n ) ) ;


"Maximum sum of cocktail glass in a 2D matrix | PHP implementation of the approach ; Function to return the maximum sum of a cocktail glass ; If no cocktail glass is possible ; Initialize max_sum with the mini ; Here loop runs ( R - 2 ) * ( C - 2 ) times considering different top left cells of cocktail glasses ; Considering mat [ i ] [ j ] as the top left cell of the cocktail glass ; Update the max_sum ; Driver code"
Solution in php:


"Maximum sum of difference of adjacent elements | To find max sum of permutation ; Base case ; Otherwise max sum will be ( n * ( n - 1 ) / 2 ) - 1 + n / 2 ; Driver Code"
Solution in php:

< ? php function maxSum ( $ n ) { if ( $ n == 1 ) return 1 ; else return ( $ n * ( $ n - 1 ) / 2 ) - 1 + $ n / 2 ; } $ n = 3 ; echo intval ( maxSum ( $ n ) ) ; ? >


"Maximum sum of distinct numbers such that LCM of these numbers is N | Returns maximum sum of numbers with LCM as N ; Initialize result ; Finding a divisor of n and adding it to max_sum ; Driver code"
Solution in php:

< ? php function maxSumLCM ( $ n ) { $ max_sum = 0 ; for ( $ i = 1 ; $ i * $ i <= $ n ; $ i ++ ) { if ( $ n % $ i == 0 ) { $ max_sum += $ i ; if ( $ n / $ i != $ i ) $ max_sum += ( $ n / $ i ) ; } } return $ max_sum ; } $ n = 2 ; echo MaxSumLCM ( $ n ) ; ? >


"Maximum sum of distinct numbers with LCM as N | Returns maximum sum of numbers with LCM as N ; Finding a divisor of n and adding it to max_sum ; if ' i ' is divisor of ' N ' ; if both divisors are same then add it only once else add both ; Driver code"
Solution in php:

 < ? php function maxSumLCM ( $ n ) { $ max_sum = 0 ; for ( $ i = 1 ; $ i * $ i <= $ n ; $ i ++ ) { if ( $ n % $ i == 0 ) { $ max_sum += $ i ; if ( $ n / $ i != $ i ) $ max_sum += ( $ n / $ i ) ; } } return $ max_sum ; } $ n = 2 ; echo MaxSumLCM ( $ n ) , "
 " ; ? >


"Maximum sum of elements from each row in the matrix | PHP Program to find row - wise maximum element sum considering elements in increasing order . ; Function to perform given task ; Getting the maximum element from last row ; Comparing it with the elements of above rows ; Maximum of current row . ; If we could not an element smaller than prev_max . ; Driver code"
Solution in php:

 < ? php $ N = 3 ; function getGreatestSum ( $ a ) { global $ N ; $ prev_max = 0 ; for ( $ j = 0 ; $ j < $ N ; $ j ++ ) if ( $ prev_max < $ a [ $ N - 1 ] [ $ j ] ) $ prev_max = $ a [ $ N - 1 ] [ $ j ] ; $ sum = $ prev_max ; for ( $ i = $ N - 2 ; $ i >= 0 ; $ i -- ) { $ curr_max = PHP_INT_MIN ; for ( $ j = 0 ; $ j < $ N ; $ j ++ ) if ( $ prev_max > $ a [ $ i ] [ $ j ] and $ a [ $ i ] [ $ j ] > $ curr_max ) $ curr_max = $ a [ $ i ] [ $ j ] ; if ( $ curr_max == PHP_INT_MIN ) return -1 ; $ prev_max = $ curr_max ; $ sum += $ prev_max ; } return $ sum ; } $ a = array ( array ( 1 , 2 , 3 ) , array ( 4 , 5 , 6 ) , array ( 7 , 8 , 9 ) ) ; echo getGreatestSum ( $ a ) , "
 " ; $ b = array ( array ( 4 , 5 , 6 ) , array ( 4 , 5 , 6 ) , array ( 4 , 5 , 6 ) ) ; echo getGreatestSum ( $ b ) , "
 " ; ? >


"Maximum sum of i * arr [ i ] among all rotations of a given array | An efficient PHP program to compute maximum sum of i * arr [ i ] ; Compute sum of all array elements ; Compute sum of i * arr [ i ] for initial configuration . ; Initialize result ; Compute values for other iterations ; Compute next value using previous value in O ( 1 ) time ; Update current value ; Update result if required ; Driver code"
Solution in php:

< ? php function maxSum ( $ arr , $ n ) { $ cum_sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ cum_sum += $ arr [ $ i ] ; $ curr_val = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ curr_val += $ i * $ arr [ $ i ] ; $ res = $ curr_val ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ next_val = $ curr_val - ( $ cum_sum - $ arr [ $ i - 1 ] ) + $ arr [ $ i - 1 ] * ( $ n - 1 ) ; $ curr_val = $ next_val ; $ res = max ( $ res , $ next_val ) ; } return $ res ; } $ arr = array ( 8 , 3 , 1 , 2 ) ; $ n = sizeof ( $ arr ) ; echo maxSum ( $ arr , $ n ) ; ? >


"Maximum sum of i * arr [ i ] among all rotations of a given array | Returns maximum value of i * arr [ i ] ; Initialize result ; Consider rotation beginning with i for all possible values of i . ; Initialize sum of current rotation ; Compute sum of all values . We don 't actually rotate  the array, but compute sum  by finding indexes when  arr[i] is first element ; Update result if required ; Driver code"
Solution in php:

 < ? php function maxSum ( $ arr , $ n ) { $ res = PHP_INT_MIN ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { $ curr_sum = 0 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { $ index = ( $ i + $ j ) % $ n ; $ curr_sum += $ j * $ arr [ $ index ] ; } $ res = max ( $ res , $ curr_sum ) ; } return $ res ; } $ arr = array ( 8 , 3 , 1 , 2 ) ; $ n = sizeof ( $ arr ) ; echo maxSum ( $ arr , $ n ) , "
 " ; ? >


"Maximum sum of increasing order elements from n arrays | PHP program to find maximum sum by selecting a element from n arrays ; To calculate maximum sum by selecting element from each array ; Sort each array ; Store maximum element of last array ; Selecting maximum element from previoulsy selected element ; j = - 1 means no element is found in a [ i ] so return 0 ; Driver Code"
Solution in php:


"Maximum sum of pairs with specific difference | Method to return maximum sum we can get by finding less than K difference pairs ; Sort elements to ensure every i and i - 1 is closest possible pair ; To get maximum possible sum , iterate from largest to smallest , giving larger numbers priority over smaller numbers . ; Case I : Diff of arr [ i ] and arr [ i - 1 ] is less then K , add to maxSum Case II : Diff between arr [ i ] and arr [ i - 1 ] is not less then K , move to next i since with sorting we know , arr [ i ] - arr [ i - 1 ] < arr [ i ] - arr [ i - 2 ] and so on . ; Assuming only positive numbers . ; When a match is found skip this pair ; Driver Code"
Solution in php:

< ? php function maxSumPairWithDifferenceLessThanK ( $ arr , $ N , $ k ) { $ maxSum = 0 ; sort ( $ arr ) ; for ( $ i = $ N - 1 ; $ i > 0 ; -- $ i ) { if ( $ arr [ $ i ] - $ arr [ $ i - 1 ] < $ k ) { $ maxSum += $ arr [ $ i ] ; $ maxSum += $ arr [ $ i - 1 ] ; -- $ i ; } } return $ maxSum ; } $ arr = array ( 3 , 5 , 10 , 15 , 17 , 12 , 9 ) ; $ N = sizeof ( $ arr ) ; $ K = 4 ; echo maxSumPairWithDifferenceLessThanK ( $ arr , $ N , $ K ) ; ? >


"Maximum sum of pairs with specific difference | method to return maximum sum we can get by finding less than K difference pair ; Sort input array in ascending order . ; dp [ i ] denotes the maximum disjoint pair sum we can achieve using first i elements ; if no element then dp value will be 0 ; first give previous value to dp [ i ] i . e . no pairing with ( i - 1 ) th element ; if current and previous element can form a pair ; update dp [ i ] by choosing maximum between pairing and not pairing ; last index will have the result ; Driver code"
Solution in php:

< ? php function maxSumPairWithDifferenceLessThanK ( $ arr , $ N , $ K ) { sort ( $ arr ) ; $ dp = array ( ) ; $ dp [ 0 ] = 0 ; for ( $ i = 1 ; $ i < $ N ; $ i ++ ) { $ dp [ $ i ] = $ dp [ $ i - 1 ] ; if ( $ arr [ $ i ] - $ arr [ $ i - 1 ] < $ K ) { if ( $ i >= 2 ) $ dp [ $ i ] = max ( $ dp [ $ i ] , $ dp [ $ i - 2 ] + $ arr [ $ i ] + $ arr [ $ i - 1 ] ) ; else $ dp [ $ i ] = max ( $ dp [ $ i ] , $ arr [ $ i ] + $ arr [ $ i - 1 ] ) ; } } return $ dp [ $ N - 1 ] ; } $ arr = array ( 3 , 5 , 10 , 15 , 17 , 12 , 9 ) ; $ N = sizeof ( $ arr ) ; $ K = 4 ; echo maxSumPairWithDifferenceLessThanK ( $ arr , $ N , $ K ) ; ? >


"Maximum sum of pairwise product in an array with negative allowed | PHP program for above implementation ; Function to find the maximum sum ; Sort the array first ; First multiply negative numbers pairwise and sum up from starting as to get maximum sum . ; Second multiply positive numbers pairwise and summed up from the last as to get maximum sum . ; To handle case if positive and negative numbers both are odd in counts . ; If one of them occurs odd times ; Driver code"
Solution in php:


"Maximum sum path in a matrix from top to bottom | PHP implementation to find the maximum sum path in a matrix ; function to find the maximum sum path in a matric ; if there is a single element only ; dp [ ] [ ] matrix to store the results of each iteration ; base case , copying elements of last row ; building up the dp [ ] [ ] matrix from bottom to the top row ; finding the maximum diagonal element in the ( i + 1 ) th row if that cell exists ; adding that ' max ' element to the mat [ i ] [ j ] element ; finding the maximum value from the first row of dp [ ] [ ] ; required maximum sum ; Driver Code"
Solution in php:


"Maximum sum subarray removing at most one element | Method returns maximum sum of all subarray where removing one element is also allowed ; Maximum sum subarrays in forward and backward directions ; Initialize current max and max so far . ; calculating maximum sum subarrays in forward direction ; storing current maximum till ith , in forward array ; calculating maximum sum subarrays in backward direction ; storing current maximum from ith , in backward array ; Initializing final ans by max_so_far so that , case when no element is removed to get max sum subarray is also handled ; choosing maximum ignoring ith element ; Driver Code"
Solution in php:

< ? php function maxSumSubarrayRemovingOneEle ( $ arr , $ n ) { $ fw = array ( ) ; $ bw = array ( ) ; $ cur_max = $ arr [ 0 ] ; $ max_so_far = $ arr [ 0 ] ; $ fw [ 0 ] = $ arr [ 0 ] ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ cur_max = max ( $ arr [ $ i ] , $ cur_max + $ arr [ $ i ] ) ; $ max_so_far = max ( $ max_so_far , $ cur_max ) ; $ fw [ $ i ] = $ cur_max ; } $ cur_max = $ max_so_far = $ bw [ $ n - 1 ] = $ arr [ $ n - 1 ] ; for ( $ i = $ n - 2 ; $ i >= 0 ; $ i -- ) { $ cur_max = max ( $ arr [ $ i ] , $ cur_max + $ arr [ $ i ] ) ; $ max_so_far = max ( $ max_so_far , $ cur_max ) ; $ bw [ $ i ] = $ cur_max ; } $ fans = $ max_so_far ; for ( $ i = 1 ; $ i < $ n - 1 ; $ i ++ ) $ fans = max ( $ fans , $ fw [ $ i - 1 ] + $ bw [ $ i + 1 ] ) ; return $ fans ; } $ arr = array ( -2 , -3 , 4 , -1 , -2 , 1 , 5 , -3 ) ; $ n = count ( $ arr ) ; echo maxSumSubarrayRemovingOneEle ( $ arr , $ n ) ; ? >


"Maximum sum subsequence with at | PHP program to find maximum sum subsequence such that elements are at least k distance away . ; We fill MS from right to left . ; Driver code"
Solution in php:


"Maximum sum such that no two elements are adjacent | Set 2 | PHP program to implement above approach ; variable to store states of dp ; variable to check if a given state has been solved ; Function to find the maximum sum subsequence such that no two elements are adjacent ; Base case ; To check if a state has been solved ; Required recurrence relation ; Returning the value ; Driver code"
Solution in php:

< ? php $ maxLen = 10 ; $ dp = array_fill ( 0 , $ GLOBALS [ ' axLen ' , 0 ) ; $ v = array_fill ( 0 , $ GLOBALS [ ' axLen ' , 0 ) ; function maxSum ( $ arr , $ i , $ n ) { if ( $ i >= $ n ) return 0 ; if ( $ GLOBALS [ ' v ' ] [ $ i ] ) return $ GLOBALS [ ' dp ' ] [ $ i ] ; $ GLOBALS [ ' v ' ] [ $ i ] = 1 ; $ GLOBALS [ ' dp ' ] [ $ i ] = max ( maxSum ( $ arr , $ i + 1 , $ n ) , $ arr [ $ i ] + maxSum ( $ arr , $ i + 2 , $ n ) ) ; return $ GLOBALS [ ' dp ' ] [ $ i ] ; } $ arr = array ( 12 , 9 , 7 , 33 ) ; $ n = count ( $ arr ) ; echo maxSum ( $ arr , 0 , $ n ) ; ? >


"Maximum trace possible for any sub | PHP implementation of the approach ; Function to return the maximum trace possible for a sub - matrix of the given matrix ; Calculate the trace for each of the sub - matrix with top left corner at cell ( r , s ) ; Update the maximum trace ; Return the maximum trace ; Driver code"
Solution in php:

< ? php $ N = 3 ; function MaxTraceSub ( $ mat ) { global $ N ; $ max_trace = 0 ; for ( $ i = 0 ; $ i < $ N ; $ i ++ ) { for ( $ j = 0 ; $ j < $ N ; $ j ++ ) { $ r = $ i ; $ s = $ j ; $ trace = 0 ; while ( $ r < $ N && $ s < $ N ) { $ trace += $ mat [ $ r ] [ $ s ] ; $ r ++ ; $ s ++ ; $ max_trace = max ( $ trace , $ max_trace ) ; } } } return $ max_trace ; } $ mat = array ( array ( 10 , 2 , 5 ) , array ( 6 , 10 , 4 ) , array ( 2 , 7 , -10 ) ) ; print ( MaxTraceSub ( $ mat ) ) ; ? >


"Maximum value of an integer for which factorial can be calculated on a machine | PHP program to find maximum value of an integer for which factorial can be calculated on your system ; when fact crosses its size , it gives negative value ; Driver Code"
Solution in php:

< ? php function findMaxValue ( ) { $ res = 2 ; $ fact = 2 ; $ pos = -1 ; while ( true ) { $ mystring = $ fact ; $ pos = strpos ( $ mystring , ' E ' ) ; if ( $ pos > 0 ) break ; $ res ++ ; $ fact = $ fact * $ res ; } return $ res - 1 ; } echo " Maximum ▁ value ▁ of " . " ▁ integer ▁ " . findMaxValue ( ) ; ? >


"Maximum value of | arr [ 0 ] | Function to return the maximum required value ; Driver code"
Solution in php:

< ? php function maxValue ( $ n ) { if ( $ n == 1 ) return 0 ; return ( ( $ n * $ n / 2 ) - 1 ) ; } $ n = 4 ; echo maxValue ( $ n ) ; ? >


"Maximum value of | arr [ i ] | PHP program to find maximum value of | arr [ i ] - arr [ j ] | + | i - j | ; Return maximum value of | arr [ i ] - arr [ j ] | + | i - j | ; Iterating two for loop , one for i and another for j . ; Evaluating | arr [ i ] - arr [ j ] | + | i - j | and compare with previous maximum . ; Driver Code"
Solution in php:

< ? php $ MAX = 10 ; function findValue ( $ arr , $ n ) { $ ans = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) for ( $ j = 0 ; $ j < $ n ; $ j ++ ) $ ans = max ( $ ans , abs ( $ arr [ $ i ] - $ arr [ $ j ] ) + abs ( $ i - $ j ) ) ; return $ ans ; } $ arr = array ( 1 , 2 , 3 , 1 ) ; $ n = count ( $ arr ) ; echo findValue ( $ arr , $ n ) ; ? >


"Maximum value of | arr [ i ] | Return maximum | arr [ i ] - arr [ j ] | + | i - j | ; Calculating first_array and second_array ; Finding maximum and minimum value in first_array ; Storing the difference between maximum and minimum value in first_array ; Finding maximum and minimum value in second_array ; Storing the difference between maximum and minimum value in second_array ; Driver Code"
Solution in php:


"Maximum value with the choice of either dividing or considering as it is | function for calculating max possible result ; Compute remaining values in bottom up manner . ; Driver Code"
Solution in php:


"Maximum weight path ending at any element of last row in a matrix | Function which return the maximum weight path sum ; creat 2D matrix to store the sum of the path ; Initialize first column of total weight array ( dp [ i to N ] [ 0 ] ) ; Calculate rest path sum of weight matrix ; find the max weight path sum to rech the last row ; return maximum weight path sum ; Driver program"
Solution in php:


"Mean of range in array | To find mean of range in l to r ; Both sum and count are initialize to 0 ; To calculate sum and number of elements in range l to r ; Calculate floor value of mean ; Returns mean of array in range l to r ; Driver Code"
Solution in php:

 < ? php function findMean ( $ arr , $ l , $ r ) { $ sum = 0 ; $ count = 0 ; for ( $ i = $ l ; $ i <= $ r ; $ i ++ ) { $ sum += $ arr [ $ i ] ; $ count ++ ; } $ mean = floor ( $ sum / $ count ) ; return $ mean ; } $ arr = array ( 1 , 2 , 3 , 4 , 5 ) ; echo findMean ( $ arr , 0 , 2 ) , "
 " ; echo findMean ( $ arr , 1 , 3 ) , "
 " ; echo findMean ( $ arr , 0 , 4 ) , "
 " ; ? >


"Mean | Function for calculating mean ; Driver Code"
Solution in php:

 < ? php function findMean ( & $ a , $ n ) { $ sum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ sum += $ a [ $ i ] ; return ( double ) $ sum / ( double ) $ n ; } $ a = array ( 1 , 3 , 4 , 2 , 7 , 5 , 8 , 6 ) ; $ n = sizeof ( $ a ) ; echo " Mean ▁ = ▁ " . findMean ( $ a , $ n ) . "
 " ; ? >


"Median after K additional integers | Find median of array after adding k elements ; sorting the array in increasing order . ; printing the median of array . Since n + K is always odd and K < n , so median of array always lies in the range of n . ; Driver Code"
Solution in php:

< ? php function printMedian ( $ arr , $ n , $ K ) { sort ( $ arr ) ; echo $ arr [ ( $ n + $ K ) / 2 ] ; } $ arr = array ( 5 , 3 , 2 , 8 ) ; $ k = 3 ; $ n = count ( $ arr ) ; printMedian ( $ arr , $ n , $ k ) ; ? >


"Median and Mode using Counting Sort | Function that sort input array a [ ] and calculate mode and median using counting sort . ; The output array b [ ] will have sorted array ; variable to store max of input array which will to have size of count array ; auxiliary ( count ) array to store count . Initialize count array as 0. Size of count array will be equal to ( max + 1 ) . ; Store count of each element of input array ; mode is the index with maximum count ; Update count [ ] array with sum ; Sorted output array b [ ] to calculate median ; Median according to odd and even array size respectively . ; Output the result ; Driver Code"
Solution in php:


"Median of two sorted arrays of different sizes | Set 1 ( Linear ) | This function returns median of a [ ] and b [ ] . Assumptions in this function : Both a [ ] and b [ ] are sorted arrays ; Current index of i / p array a [ ] ; Current index of i / p array b [ ] ; Below is to handle the case where all elements of a [ ] are smaller than smallest ( or first ) element of b [ ] or a [ ] is empty ; Below is to handle case where all elements of b [ ] are smaller than smallest ( or first ) element of a [ ] or b [ ] is empty ; Below is to handle the case where sum of number of elements of the arrays is even ; Below is to handle the case where sum of number of elements of the arrays is odd ; Driver Code"
Solution in php:


"Median of two sorted arrays of same size | This function returns median of ar1 [ ] and ar2 [ ] . Assumptions in this function : Both ar1 [ ] and ar2 [ ] are sorted arrays Both have n elements ; Since there are 2 n elements , median will be average of elements at index n - 1 and n in the array obtained after merging ar1 and ar2 ; Below is to handle case where all elements of ar1 [ ] are smaller than smallest ( or first ) element of ar2 [ ] ; Below is to handle case where all elements of ar2 [ ] are smaller than smallest ( or first ) element of ar1 [ ] ; equals sign because if two arrays have some common elements ; Store the prev median ; Store the prev median ; Driver Code"
Solution in php:


"Median of two sorted arrays with different sizes in O ( log ( min ( n , m ) ) ) | PHP code for median with case of returning double value when even number of elements are present in both array combinely ; Function to find max ; Function to find minimum ; Function to find median of two sorted arrays ; if i = n , it means that Elements from a [ ] in the second half is an empty set . and if j = 0 , it means that Elements from b [ ] in the first half is an empty set . so it is necessary to check that , because we compare elements from these two groups . Searching on right ; if i = 0 , it means that Elements from a [ ] in the first half is an empty set and if j = m , it means that Elements from b [ ] in the second half is an empty set . so it is necessary to check that , because we compare elements from these two groups . searching on left ; we have found the desired halves . ; this condition happens when we don 't have any elements  in the first half from a[]  so we returning the last  element in b[] from the  first half. ; and this condition happens when we don 't have any  elements in the first half  from b[] so we returning the  last element in a[] from the  first half. ; calculating the median . If number of elements is odd there is one middle element . ; Elements from a [ ] in the second half is an empty set . ; Elements from b [ ] in the second half is an empty set . ; Driver code ; we need to define the smaller array as the first parameter to make sure that the time complexity will be O ( log ( min ( n , m ) ) )"
Solution in php:

< ? php $ median = 0 ; $ i = 0 ; $ j = 0 ; function maximum ( $ a , $ b ) { return $ a > $ b ? $ a : $ b ; } function minimum ( $ a , $ b ) { return $ a < $ b ? $ a : $ b ; } function findMedianSortedArrays ( & $ a , $ n , & $ b , $ m ) { global $ median , $ i , $ j ; $ min_index = 0 ; $ max_index = $ n ; while ( $ min_index <= $ max_index ) { $ i = intval ( ( $ min_index + $ max_index ) / 2 ) ; $ j = intval ( ( ( $ n + $ m + 1 ) / 2 ) - $ i ) ; if ( $ i < $ n && $ j > 0 && $ b [ $ j - 1 ] > $ a [ $ i ] ) $ min_index = $ i + 1 ; else if ( $ i > 0 && $ j < $ m && $ b [ $ j ] < $ a [ $ i - 1 ] ) $ max_index = $ i - 1 ; else { if ( $ i == 0 ) $ median = $ b [ $ j - 1 ] ; else if ( $ j == 0 ) $ median = $ a [ $ i - 1 ] ; else $ median = maximum ( $ a [ $ i - 1 ] , $ b [ $ j - 1 ] ) ; break ; } } if ( ( $ n + $ m ) % 2 == 1 ) return $ median ; if ( $ i == $ n ) return ( ( $ median + $ b [ $ j ] ) / 2.0 ) ; if ( $ j == $ m ) return ( ( $ median + $ a [ $ i ] ) / 2.0 ) ; return ( ( $ median + minimum ( $ a [ $ i ] , $ b [ $ j ] ) ) / 2.0 ) ; } $ a = array ( 900 ) ; $ b = array ( 10 , 13 , 14 ) ; $ n = count ( $ a ) ; $ m = count ( $ b ) ; if ( $ n < $ m ) echo ( " The ▁ median ▁ is ▁ : ▁ " . findMedianSortedArrays ( $ a , $ n , $ b , $ m ) ) ; else echo ( " The ▁ median ▁ is ▁ : ▁ " . findMedianSortedArrays ( $ b , $ m , $ a , $ n ) ) ; ? >


"Median | Function for calculating median ; First we sort the array ; check for even case ; Driver Code"
Solution in php:

< ? php function findMedian ( & $ a , $ n ) { sort ( $ a ) ; if ( $ n % 2 != 0 ) return ( double ) $ a [ $ n / 2 ] ; return ( double ) ( $ a [ ( $ n - 1 ) / 2 ] + $ a [ $ n / 2 ] ) / 2.0 ; } $ a = array ( 1 , 3 , 4 , 2 , 7 , 5 , 8 , 6 ) ; $ n = sizeof ( $ a ) ; echo " Median ▁ = ▁ " . findMedian ( $ a , $ n ) ; ? >


"Memoization ( 1D , 2D and 3D ) | Fibonacci Series using Recursion ; Base case ; recursive calls ; Driver Code"
Solution in php:

< ? php function fib ( $ n ) { if ( $ n <= 1 ) return $ n ; return fib ( $ n - 1 ) + fib ( $ n - 2 ) ; } $ n = 6 ; echo fib ( $ n ) ; ? >


"Merge K sorted arrays | Set 3 ( Using Divide and Conquer Approach ) | PHP program to merge K sorted arrays ; Function to perform merge operation ; to store the starting point of left and right array ; to store the size of left and right array ; array to temporarily store left and right array ; storing data in left array ; storing data in right array ; to store the current index of temporary left and right array ; to store the current index for output array ; two pointer merge for two sorted arrays ; Code to drive merge - sort and create recursion tree ; base step to initialize the output array before performing merge operation ; to sort left half ; to sort right half ; merge the left and right half ; input 2D - array ; Number of arrays ; Output array ; Print merged array"
Solution in php:


"Merge an array of size n into another array of size m + n | Assuming - 1 is filled for the places where element is not available ; Function to move m elements at the end of array mPlusN [ ] ; Merges array N [ ] of size n into array mPlusN [ ] of size m + n ; Current index of i / p part of mPlusN [ ] ; Current index of N [ ] ; Current index of output mPlusN [ ] ; Take an element from mPlusN [ ] if a ) value of the picked element is smaller and we have not reached end of it b ) We have reached end of N [ ] ; Otherwise take element from N [ ] ; Utility that prints out an array on a line ; Initialize arrays ; Move the m elements at the end of mPlusN ; Merge N [ ] into mPlusN [ ] ; Print the resultant mPlusN"
Solution in php:

 < ? php $ NA = -1 ; function moveToEnd ( & $ mPlusN , $ size ) { global $ NA ; $ j = $ size - 1 ; for ( $ i = $ size - 1 ; $ i >= 0 ; $ i -- ) if ( $ mPlusN [ $ i ] != $ NA ) { $ mPlusN [ $ j ] = $ mPlusN [ $ i ] ; $ j -- ; } } function merge ( & $ mPlusN , & $ N , $ m , $ n ) { $ i = $ n ; $ j = 0 ; $ k = 0 ; while ( $ k < ( $ m + $ n ) ) { if ( ( $ j == $ n ) || ( $ i < ( $ m + $ n ) && $ mPlusN [ $ i ] <= $ N [ $ j ] ) ) { $ mPlusN [ $ k ] = $ mPlusN [ $ i ] ; $ k ++ ; $ i ++ ; } else { $ mPlusN [ $ k ] = $ N [ $ j ] ; $ k ++ ; $ j ++ ; } } } function printArray ( & $ arr , $ size ) { for ( $ i = 0 ; $ i < $ size ; $ i ++ ) echo $ arr [ $ i ] . " ▁ " ; echo "
 " ; } $ mPlusN = array ( 2 , 8 , $ NA , $ NA , $ NA , 13 , $ NA , 15 , 20 ) ; $ N = array ( 5 , 7 , 9 , 25 ) ; $ n = sizeof ( $ N ) ; $ m = sizeof ( $ mPlusN ) - $ n ; moveToEnd ( $ mPlusN , $ m + $ n ) ; merge ( $ mPlusN , $ N , $ m , $ n ) ; printArray ( $ mPlusN , $ m + $ n ) ; ? >


"Merge two sorted arrays with O ( 1 ) extra space | Merge ar1 [ ] and ar2 [ ] with O ( 1 ) extra space ; Iterate through all elements of ar2 [ ] starting from the last element ; Find the smallest element greater than ar2 [ i ] . Move all elements one position ahead till the smallest greater element is not found ; If there was a greater element ; Driver program"
Solution in php:


"Merge two sorted arrays | Merge $arr1 [ 0. . $n1 - 1 ] and $arr2 [ 0. . $n2 - 1 ] into $arr3 [ 0. . $n1 + $n2 - 1 ] ; Traverse both array ; Check if current element of first array is smaller than current element of second array . If yes , store first array element and increment first array index . Otherwise do same with second array ; Store remaining elements of first array ; Store remaining elements of second array ; Driver code"
Solution in php:


"Mersenne Prime | Generate all prime numbers less than n . ; Initialize all entries of boolean array as true . A value in prime [ i ] will finally be false if i is Not a prime , else true ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to generate mersenne primes less than or equal to n ; Generating primes using Sieve ; Generate all numbers of the form 2 ^ k - 1 and smaller than or equal to n . ; Checking whether number is prime and is one less then the power of 2 ; Driver Code"
Solution in php:

< ? php function SieveOf ( $ n ) { $ prime = array ( $ n + 1 ) ; for ( $ i = 0 ; $ i <= $ n ; $ i ++ ) $ prime [ $ i ] = true ; for ( $ p = 2 ; $ p * $ p <= $ n ; $ p ++ ) { if ( $ prime [ $ p ] == true ) { for ( $ i = $ p * 2 ; $ i <= $ n ; $ i += $ p ) $ prime [ $ i ] = false ; } } return $ prime ; } function mersennePrimes ( $ n ) { $ prime = SieveOf ( $ n ) ; for ( $ k = 2 ; ( ( 1 << $ k ) - 1 ) <= $ n ; $ k ++ ) { $ num = ( 1 << $ k ) - 1 ; if ( $ prime [ $ num ] ) echo $ num . " " ; } } $ n = 31 ; echo " Mersenne ▁ prime ▁ numbers ▁ smaller ▁ " . " than ▁ or ▁ equal ▁ to ▁ $ n ▁ " . mersennePrimes ( $ n ) ; ? >


"Meta Binary Search | One | Function to show the working of Meta binary search ; Set number of bits to represent ; largest array index This is redundant and will cause error for some case while ( ( 1 << $lg ) < $n - 1 ) $lg += 1 ; ; Incrementally construct the index of the target value ; find the element in one direction and update $position ; if element found return $pos otherwise - 1 ; Driver code"
Solution in php:

< ? php function bsearch ( $ A , $ key_to_search , $ n ) { $ lg = log ( $ n - 1 , 2 ) + 1 ; $ pos = 0 ; for ( $ i = $ lg - 1 ; $ i >= 0 ; $ i -- ) { if ( $ A [ $ pos ] == $ key_to_search ) return $ pos ; $ new_pos = $ pos | ( 1 << $ i ) ; if ( ( $ new_pos < $ n ) && ( $ A [ $ new_pos ] <= $ key_to_search ) ) $ pos = $ new_pos ; } return ( ( $ A [ $ pos ] == $ key_to_search ) ? $ pos : -1 ) ; } $ A = [ -2 , 10 , 100 , 250 , 32315 ] ; $ ans = bsearch ( $ A , 10 , 5 ) ; echo $ ans ; ? >


"Midpoint ellipse drawing algorithm | PHP program for implementing Mid - Point Ellipse Drawing Algorithm ; Initial decision parameter of region 1 ; For region 1 ; Print points based on 4 - way symmetry ; Checking and updating value of decision parameter based on algorithm ; Decision parameter of region 2 ; Plotting points of region 2 ; printing points based on 4 - way symmetry ; Checking and updating parameter value based on algorithm ; To draw a ellipse of major and minor radius 15 , 10 centred at ( 50 , 50 )"
Solution in php:


"Min Cost Path | DP | A Naive recursive implementation of MCP ( Minimum Cost Path ) problem ; A utility function that returns minimum of 3 integers ; Returns cost of minimum cost path from ( 0 , 0 ) to ( m , n ) in mat [ R ] [ C ] ; Driver Code"
Solution in php:

< ? php $ R = 3 ; $ C = 3 ; function min1 ( $ x , $ y , $ z ) { if ( $ x < $ y ) return ( $ x < $ z ) ? $ x : $ z ; else return ( $ y < $ z ) ? $ y : $ z ; } function minCost ( $ cost , $ m , $ n ) { global $ R ; global $ C ; if ( $ n < 0 $ m < 0 ) return PHP_INT_MAX ; else if ( $ m == 0 && $ n == 0 ) return $ cost [ $ m ] [ $ n ] ; else return $ cost [ $ m ] [ $ n ] + min1 ( minCost ( $ cost , $ m - 1 , $ n - 1 ) , minCost ( $ cost , $ m - 1 , $ n ) , minCost ( $ cost , $ m , $ n - 1 ) ) ; } $ cost = array ( array ( 1 , 2 , 3 ) , array ( 4 , 8 , 2 ) , array ( 1 , 5 , 3 ) ) ; echo minCost ( $ cost , 2 , 2 ) ; ? >


"Min Cost Path | DP | DP implementation of MCP problem ; Instead of following line , we can use int tc [ m + 1 ] [ n + 1 ] or dynamically allocate memory to save space . The following line is used to keep the program simple and make it working on all compilers . ; Initialize first column of total cost ( tc ) array ; Initialize first row of tc array ; Construct rest of the tc array ; returns minimum of 3 integers ; Driver Code"
Solution in php:


"Min flips of continuous characters to make all characters same in a string | To find min number of flips in binary string ; If last character is not equal to str [ i ] increase res ; To return min flips ; Driver Code"
Solution in php:

< ? php function findFlips ( $ str , $ n ) { $ last = ' ▁ ' ; $ res = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ last != $ str [ $ i ] ) $ res ++ ; $ last = $ str [ $ i ] ; } return intval ( $ res / 2 ) ; } $ str = "00011110001110" ; $ n = strlen ( $ str ) ; echo findFlips ( $ str , $ n ) ; ? >


"Minimal moves to form a string by adding characters or appending string itself | function to return the minimal number of moves ; initializing dp [ i ] to INT_MAX ; initialize both strings to null ; base case ; check if it can be appended ; addition of character takes one step ; appending takes 1 step , and we directly reach index i * 2 + 1 after appending so the number of steps is stord in i * 2 + 1 ; Driver Code ; function call to return minimal number of moves"
Solution in php:


"Minimal operations to make a number magical | function to calculate the minimal changes ; maximum digits that can be changed ; nested loops to generate all 6 digit numbers ; counter to count the number of change required ; if first digit is equal ; if 2 nd digit is equal ; if 3 rd digit is equal ; if 4 th digit is equal ; if 5 th digit is equal ; if 6 th digit is equal ; checks if less then the previous calculate changes ; returns the answer ; number stored in string ; prints the minimum operations"
Solution in php:


"Minimize ( max ( A [ i ] , B [ j ] , C [ k ] ) | PHP code for above approach ; calculating min difference from last index of lists ; checking condition ; calculating max term from list ; Moving to smaller value in the array with maximum out of three . ; Driver code"
Solution in php:


"Minimize Cost with Replacement with other allowed | this function returns the minimum cost of the array ; Code driven"
Solution in php:

 < ? php function getMinCost ( $ arr , $ n ) { $ min_ele = min ( $ arr ) ; return $ min_ele * ( $ n - 1 ) ; } $ arr = array ( 4 , 2 , 5 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; echo getMinCost ( $ arr , $ n ) ; #This  code contributed by ajit
? >


"Minimize sum of adjacent difference with removal of one element from array | Function to find the element ; Value variable for storing the total value ; Declaring maximum value as zero ; If array contains on element ; Storing the maximum value in temp variable ; Adding the adjacent difference modulus values of removed element . Removing adjacent difference modulus value after removing element ; Returning total value - maximum value ; Drivers code"
Solution in php:

< ? php function findMinRemoval ( $ arr , $ n ) { $ value = 0 ; $ maximum = 0 ; if ( $ n == 1 ) return 0 ; $ temp = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ i != 0 && $ i != $ n - 1 ) { $ value = $ value + abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ; $ temp = abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) + abs ( $ arr [ $ i ] - $ arr [ $ i - 1 ] ) - abs ( $ arr [ $ i - 1 ] - $ arr [ $ i + 1 ] ) ; } else if ( $ i == 0 ) { $ value = $ value + abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ; $ temp = abs ( $ arr [ $ i ] - $ arr [ $ i + 1 ] ) ; } else $ temp = abs ( $ arr [ $ i ] - $ arr [ $ i - 1 ] ) ; $ maximum = max ( $ maximum , $ temp ) ; } return ( $ value - $ maximum ) ; } $ arr = array ( 1 , 5 , 3 , 2 , 10 ) ; $ n = count ( $ arr ) ; echo findMinRemoval ( $ arr , $ n ) ; ? >


"Minimize the absolute difference of sum of two subsets | function to print difference ; summation of n elements ; if divisible by 4 ; if remainder 1 or 2. In case of remainder 2 , we divide elements from 3 to n in groups of size 4 and put 1 in one group and 2 in group . This also makes difference 1. ; We put elements from 4 to n in groups of size 4. Remaining elements 1 , 2 and 3 can be divided as ( 1 , 2 ) and ( 3 ) . ; Driver code"
Solution in php:

< ? php function subsetDifference ( $ n ) { $ s = $ n * ( $ n + 1 ) / 2 ; if ( $ n % 4 == 0 ) { echo " First ▁ subset ▁ sum ▁ = ▁ " , floor ( $ s / 2 ) ; echo " Second subset sum = " , floor ( $ s / 2 ) ; echo " Difference = " } else { if ( $ n % 4 == 1 $ n % 4 == 2 ) { echo " First ▁ subset ▁ sum ▁ = ▁ " , floor ( $ s / 2 ) ; echo " Second subset sum = " , floor ( $ s / 2 + 1 ) ; echo " Difference = " } else { echo " First ▁ subset ▁ sum ▁ = ▁ " , floor ( $ s / 2 ) ; echo " Second subset sum = " , floor ( $ s / 2 ) ; echo " Difference = " ▁ , ▁ 0 ; } } } $ n = 6 ; subsetDifference ( $ n ) ; ? >


"Minimize the cost to split a number | check if a number is prime or not ; run a loop upto square root of x ; Function to return the minimized cost ; If n is prime ; If n is odd and can be split into ( prime + 2 ) then cost will be 1 + 1 = 2 ; Every non - prime even number can be expressed as the sum of two primes ; n is odd so n can be split into ( 3 + even ) further even part can be split into ( prime + prime ) ( 3 + prime + prime ) will cost 3 ; Driver code"
Solution in php:

< ? php function isPrime ( $ x ) { for ( $ i = 2 ; $ i * $ i <= $ x ; $ i ++ ) { if ( $ x % $ i == 0 ) return 0 ; } return 1 ; } function minimumCost ( $ n ) { if ( isPrime ( $ n ) ) return 1 ; if ( $ n % 2 == 1 && isPrime ( $ n - 2 ) ) return 2 ; if ( $ n % 2 == 0 ) return 2 ; return 3 ; } $ n = 6 ; echo ( minimumCost ( $ n ) ) ;


"Minimize the difference between minimum and maximum elements | Function to minimize the difference between minimum and maximum elements ; Find max and min elements of the array ; Check whether the difference between the max and min element is less than or equal to k or not ; Calculate average of max and min ; If the array element is greater than the average then decrease it by k ; If the array element is smaller than the average then increase it by k ; Find max and min of the modified array ; return the new difference ; Driver code"
Solution in php:

 < ? php function minimizeDiff ( & $ arr , $ n , $ k ) { $ max = max ( $ arr ) ; $ min = min ( $ arr ) ; if ( ( $ max - $ min ) <= $ k ) { return ( $ max - $ min ) ; } $ avg = ( $ max + $ min ) / 2 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] > $ avg ) $ arr [ $ i ] -= $ k ; else $ arr [ $ i ] += $ k ; } $ max = max ( $ arr ) ; $ min = min ( $ arr ) ; return ( $ max - $ min ) ; } $ arr = array ( 3 , 16 , 12 , 9 , 20 ) ; $ n = 5 ; $ k = 3 ; echo " Max ▁ height ▁ difference ▁ = ▁ " . minimizeDiff ( $ arr , $ n , $ k ) . "
 " ; ? >


"Minimize the maximum minimum difference after one removal from array | Function to return the minimum required difference ; If current element is greater than max ; max will become secondMax ; Update the max ; If current element is greater than secondMax but smaller than max ; Update the secondMax ; If current element is smaller than min ; min will become secondMin ; Update the min ; If current element is smaller than secondMin but greater than min ; Update the secondMin ; Minimum of the two possible differences ; Driver code"
Solution in php:

< ? php function findMinDifference ( $ arr , $ n ) { $ min__ = $ secondMax = ( $ arr [ 0 ] < $ arr [ 1 ] ) ? $ arr [ 0 ] : $ arr [ 1 ] ; $ max__ = $ secondMin = ( $ arr [ 0 ] < $ arr [ 1 ] ) ? $ arr [ 1 ] : $ arr [ 0 ] ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] > $ max__ ) { $ secondMax = $ max__ ; $ max__ = $ arr [ $ i ] ; } else if ( $ arr [ $ i ] > $ secondMax ) { $ secondMax = $ arr [ $ i ] ; } else if ( $ arr [ $ i ] < $ min__ ) { $ secondMin = $ min__ ; $ min__ = $ arr [ $ i ] ; } else if ( $ arr [ $ i ] < $ secondMin ) { $ secondMin = $ arr [ $ i ] ; } } $ diff = min ( $ max__ - $ secondMin , $ secondMax - $ min__ ) ; return $ diff ; } $ arr = array ( 1 , 2 , 4 , 3 , 4 ) ; $ n = count ( $ arr ) ; print ( findMinDifference ( $ arr , $ n ) ) ; ? >


"Minimize the maximum minimum difference after one removal from array | Function to return the minimum required difference ; Sort the given array ; When minimum element is removed ; When maximum element is removed ; Return the minimum of diff1 and diff2 ; Driver Code"
Solution in php:

< ? php function findMinDifference ( $ arr , $ n ) { sort ( $ arr , 0 ) ; $ diff1 = $ arr [ $ n - 1 ] - $ arr [ 1 ] ; $ diff2 = $ arr [ $ n - 2 ] - $ arr [ 0 ] ; return min ( $ diff1 , $ diff2 ) ; } $ arr = array ( 1 , 2 , 4 , 3 , 4 ) ; $ n = sizeof ( $ arr ) ; echo findMinDifference ( $ arr , $ n ) ;


"Minimize the number of replacements to get a string with same number of ' a ' , ' b ' and ' c ' in it | Function to count numbers ; Count the number of ' a ' , ' b ' and ' c ' in string ; If equal previously ; If not a multiple of 3 ; Increase the number of a ' s ▁ by ▁ ▁ ▁ removing ▁ extra ▁ ' b ' and ;c;  ; Check if it is ' b ' and it is more than n / 3 ; Check if it is ' c ' and it more than n / 3 ; Increase the number of b ' s ▁ by ▁ ▁ ▁ removing ▁ extra ▁ ' c '  ; Check if it is ' c ' and it more than n / 3 ; Increase the number of c 's from back  ; Check if it is ' a ' and it is more than n / 3 ; Increase the number of b 's from back  ; Check if it is ' a ' and it is more than n / 3 ; Increase the number of c 's from back  ; Check if it is ' b ' and it more than n / 3 ; Driver Code"
Solution in php:


"Minimize the sum of product of two arrays with permutations allowed | Returns minimum sum of product of two arrays with permutations allowed ; Sort A and B so that minimum and maximum value can easily be fetched . ; Multiplying minimum value of A and maximum value of B ; Driver Code"
Solution in php:

< ? php function minValue ( $ A , $ B , $ n ) { sort ( $ A ) ; sort ( $ A , $ n ) ; sort ( $ B ) ; sort ( $ B , $ n ) ; $ result = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ result += ( $ A [ $ i ] * $ B [ $ n - $ i - 1 ] ) ; return $ result ; } $ A = array ( 3 , 1 , 1 ) ; $ B = array ( 6 , 5 , 4 ) ; $ n = sizeof ( $ A ) / sizeof ( $ A [ 0 ] ) ; echo minValue ( $ A , $ B , $ n ) ; ? >


"Minimize the sum of the squares of the sum of elements of each group the array is divided into | Function to return the minimized sum ; Sort the array to pair the elements ; Variable to hold the answer ; Pair smallest with largest , second smallest with second largest , and so on ; Driver code"
Solution in php:

< ? php function findAnswer ( $ n , $ arr ) { sort ( $ arr ) ; $ sum = 0 ; for ( $ i = 0 ; $ i < $ n / 2 ; ++ $ i ) { $ sum += ( $ arr [ $ i ] + $ arr [ $ n - $ i - 1 ] ) * ( $ arr [ $ i ] + $ arr [ $ n - $ i - 1 ] ) ; } return $ sum ; } $ arr = array ( 53 , 28 , 143 , 5 ) ; $ n = count ( $ arr ) ; echo findAnswer ( $ n , $ arr ) ; ? >


"Minimize the value of N by applying the given operations | function to return the product of distinct prime factors of a number ; find distinct prime ; Driver code"
Solution in php:

 < ? php function minimum ( $ n ) { $ product = 1 ; for ( $ i = 2 ; $ i * $ i <= $ n ; $ i ++ ) { if ( $ n % $ i == 0 ) { while ( $ n % $ i == 0 ) $ n = $ n / $ i ; $ product = $ product * $ i ; } } if ( $ n >= 2 ) $ product = $ product * $ n ; return $ product ; } $ n = 20 ; echo minimum ( $ n ) , "
 " ; ? >


"Minimum Cost To Make Two Strings Identical | Returns length of LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains length of LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; L [ m ] [ n ] contains length of LCS for X [ 0. . n - 1 ] and Y [ 0. . m - 1 ] ; Returns cost of making X [ ] and Y [ ] identical . costX is cost of removing a character from X [ ] and costY is cost of removing a character from Y [ ] / ; Find LCS of X [ ] and Y [ ] ; Cost of making two strings identical is SUM of following two 1 ) Cost of removing extra characters from first string 2 ) Cost of removing extra characters from second string ; Driver program to test above function"
Solution in php:

< ? php function lcs ( $ X , $ Y , $ m , $ n ) { $ L = array_fill ( 0 , ( $ m + 1 ) , array_fill ( 0 , ( $ n + 1 ) , NULL ) ) ; for ( $ i = 0 ; $ i <= $ m ; $ i ++ ) { for ( $ j = 0 ; $ j <= $ n ; $ j ++ ) { if ( $ i == 0 $ j == 0 ) $ L [ $ i ] [ $ j ] = 0 ; else if ( $ X [ $ i - 1 ] == $ Y [ $ j - 1 ] ) $ L [ $ i ] [ $ j ] = $ L [ $ i - 1 ] [ $ j - 1 ] + 1 ; else $ L [ $ i ] [ $ j ] = max ( $ L [ $ i - 1 ] [ $ j ] , $ L [ $ i ] [ $ j - 1 ] ) ; } } return $ L [ $ m ] [ $ n ] ; } function findMinCost ( & $ X , & $ Y , $ costX , $ costY ) { $ m = strlen ( $ X ) ; $ n = strlen ( $ Y ) ; $ len_LCS = lcs ( $ X , $ Y , $ m , $ n ) ; return $ costX * ( $ m - $ len_LCS ) + $ costY * ( $ n - $ len_LCS ) ; } $ X = " ef " ; $ Y = " gh " ; echo " Minimum ▁ Cost ▁ to ▁ make ▁ two ▁ strings ▁ " . " identical is = " return 0 ; ? >


"Minimum Cuts can be made in the Chessboard such that it is not divided into 2 parts | function that calculates the maximum no . of cuts ; Driver Code ; Calling function ."
Solution in php:

< ? php function numberOfCuts ( $ M , $ N ) { $ result = 0 ; $ result = ( $ M - 1 ) * ( $ N - 1 ) ; return $ result ; } $ M = 4 ; $ N = 4 ; $ Cuts = numberOfCuts ( $ M , $ N ) ; echo " Maximum ▁ cuts ▁ = ▁ " , $ Cuts ; ? >


"Minimum De | function to count Dearrangement ; create a copy of original array ; sort the array ; traverse sorted array for counting mismatches ; reverse the sorted array ; traverse reverse sorted array for counting mismatches ; return minimum mismatch count ; Driver Code"
Solution in php:

< ? php function countDe ( $ arr , $ n ) { $ v = $ arr ; sort ( $ arr ) ; $ count1 = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] != $ v [ $ i ] ) $ count1 ++ ; rsort ( $ arr ) ; $ count2 = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) if ( $ arr [ $ i ] != $ v [ $ i ] ) $ count2 ++ ; return ( min ( $ count1 , $ count2 ) ) ; } $ arr = array ( 5 , 9 , 21 , 17 , 13 ) ; $ n = count ( $ arr ) ; echo " Minimum ▁ Dearrangement ▁ = ▁ " . countDe ( $ arr , $ n ) ; ? >


"Minimum Increment / decrement to make array elements equal | Function to return minimum operations need to be make each element of array equal ; Initialize cost to 0 ; Sort the array ; Middle element ; Find Cost ; If n , is even . Take minimum of the Cost obtained by considering both middle elements ; Find cost again ; Take minimum of two cost ; Return total cost ; Driver Code"
Solution in php:

< ? php function minCost ( $ A , $ n ) { $ cost = 0 ; sort ( $ A ) ; $ K = $ A [ $ n / 2 ] ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) $ cost += abs ( $ A [ $ i ] - $ K ) ; if ( $ n % 2 == 0 ) { $ tempCost = 0 ; $ K = $ A [ ( $ n / 2 ) - 1 ] ; for ( $ i = 0 ; $ i < $ n ; ++ $ i ) $ tempCost += abs ( $ A [ $ i ] - $ K ) ; $ cost = min ( $ cost , $ tempCost ) ; } return $ cost ; } $ A = array ( 1 , 6 , 7 , 10 ) ; $ n = sizeof ( $ A ) ; echo minCost ( $ A , $ n ) ; ? >


"Minimum Initial Points to Reach Destination | PHP program to find minimum initial points to reach destination ; dp [ i ] [ j ] represents the minimum initial points player should have so that when starts with cell ( i , j ) successfully reaches the destination cell ( m - 1 , n - 1 ) ; Base case ; Fill last row and last column as base to fill entire table ; fill the table in bottom - up fashion ; Driver Code"
Solution in php:


"Minimum K such that every substring of length atleast K contains a character c | This function checks if there exists some character which appears in all K length substrings ; Iterate over all possible characters ; stores the last occurrence ; set answer as true ; ; No occurrence found of current character in first substring of length K ; Check for every last substring of length K where last occurr - ence exists in substring ; If last occ is not present in substring ; current character is K amazing ; This function performs binary search over the answer to minimise it ; Check if answer is found try to minimise it ; Driver Code"
Solution in php:

 < ? php function check ( $ s , $ K ) { for ( $ ch = 0 ; $ ch < 26 ; $ ch ++ ) { $ c = chr ( ord ( ' a ' ) + $ ch ) ; $ last = -1 ; $ found = true ; for ( $ i = 0 ; $ i < $ K ; $ i ++ ) if ( $ s [ $ i ] == $ c ) $ last = $ i ; if ( $ last == -1 ) continue ; for ( $ i = $ K ; $ i < strlen ( $ s ) ; $ i ++ ) { if ( $ s [ $ i ] == $ c ) $ last = $ i ; if ( $ last <= ( $ i - $ K ) ) { $ found = false ; break ; } } if ( $ found ) return 1 ; } return 0 ; } function binarySearch ( $ s ) { $ low = 1 ; $ high = strlen ( $ s ) ; while ( $ low <= $ high ) { $ mid = ( $ high + $ low ) >> 1 ; if ( check ( $ s , $ mid ) ) { $ ans = $ mid ; $ high = $ mid - 1 ; } else $ low = $ mid + 1 ; } return $ ans ; } $ s = " abcde " ; echo binarySearch ( $ s ) . "
 " ; $ s = " aaaa " ; echo binarySearch ( $ s ) . "
 " ; ? >


"Minimum Number of Manipulations required to make two Strings Anagram Without Deletion of Character | Counts the no of manipulations required ; store the count of character ; iterate though the first String and update count ; iterate through the second string update char_count . if character is not found in char_count then increase count ; Driver code"
Solution in php:

< ? php function countManipulations ( $ s1 , $ s2 ) { $ count = 0 ; $ char_count = array_fill ( 0 , 26 , 0 ) ; for ( $ i = 0 ; $ i < strlen ( $ s1 ) ; $ i ++ ) $ char_count [ ord ( $ s1 [ $ i ] ) - ord ( ' a ' ) ] += 1 ; for ( $ i = 0 ; $ i < strlen ( $ s2 ) ; $ i ++ ) { $ char_count [ ord ( $ s2 [ $ i ] ) - ord ( ' a ' ) ] -= 1 ; } for ( $ i = 0 ; $ i < 26 ; $ i ++ ) { if ( $ char_count [ i ] != 0 ) { $ count += abs ( $ char_count [ i ] ) ; } } return $ count ; } $ s1 = " ddcf " ; $ s2 = " cedk " ; echo countManipulations ( $ s1 , $ s2 ) ; ? >


"Minimum Perimeter of n blocks | PHP program to find minimum perimeter using n blocks . ; if n is a perfect square ; Number of rows ; perimeter of the rectangular grid ; if there are blocks left ; Driver code"
Solution in php:

< ? php function minPerimeter ( $ n ) { $ l = floor ( sqrt ( $ n ) ) ; $ sq = $ l * $ l ; if ( $ sq == $ n ) return $ l * 4 ; else { $ row = floor ( $ n / $ l ) ; $ perimeter = 2 * ( $ l + $ row ) ; if ( $ n % $ l != 0 ) $ perimeter += 2 ; return $ perimeter ; } } $ n = 10 ; echo minPerimeter ( $ n ) ; ? >


"Minimum Players required to win the game | function to calculate ( a ^ b ) % ( 10 ^ 9 + 7 ) . ; function to find the minimum required player ; computing the nenomenator ; computing modulo inverse of denominator ; final result ; Driver code"
Solution in php:

< ? php function power ( $ a , $ b ) { $ mod = 1000000007 ; $ res = 1 ; while ( $ b ) { if ( $ b & 1 ) { $ res *= $ a ; $ res %= $ mod ; } $ b /= 2 ; $ a *= $ a ; $ a %= $ mod ; } return $ res ; } function minPlayer ( $ n , $ k ) { $ mod = 1000000007 ; $ num = ( ( power ( $ k , $ n ) - 1 ) + $ mod ) % $ mod ; $ den = ( power ( $ k - 1 , $ mod - 2 ) + $ mod ) % $ mod ; $ ans = ( ( ( $ num * $ den ) % $ mod ) * $ k ) % $ mod ; return $ ans ; } $ n = 3 ; $ k = 3 ; echo minPlayer ( $ n , $ k ) ; ? >


"Minimum Possible value of | ai + aj | function for finding pairs and min value ; initialize smallest and count ; iterate over all pairs ; is abs value is smaller than smallest update smallest and reset count to 1 ; if abs value is equal to smallest increment count value ; print result ; Driver Code"
Solution in php:

 < ? php function pairs ( $ arr , $ n , $ k ) { $ smallest = PHP_INT_MAX ; $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) for ( $ j = $ i + 1 ; $ j < $ n ; $ j ++ ) { if ( abs ( $ arr [ $ i ] + $ arr [ $ j ] - $ k ) < $ smallest ) { $ smallest = abs ( $ arr [ $ i ] + $ arr [ $ j ] - $ k ) ; $ count = 1 ; } else if ( abs ( $ arr [ $ i ] + $ arr [ $ j ] - $ k ) == $ smallest ) $ count ++ ; } echo " Minimal Value = " ▁ , ▁ $ smallest ▁ , ▁ " " ;
 	 	 echo ▁ " Total Pairs = " , ▁ $ count ▁ , ▁ " " } $ arr = array ( 3 , 5 , 7 , 5 , 1 , 9 , 9 ) ; $ k = 12 ; $ n = sizeof ( $ arr ) ; pairs ( $ arr , $ n , $ k ) ; ? >


"Minimum Sum Path in a Triangle | Util function to find minimum sum for a path ; For storing the result in a 1 - D array , and simultaneously updating the result . ; For the bottom row ; Calculation of the remaining rows , in bottom up manner . ; return the top element ; Driver Code"
Solution in php:


"Minimum absolute difference between N and a power of 2 | Function to return the minimum difference between N and a power of 2 ; Power of 2 closest to n on its left ; Power of 2 closest to n on its right ; Return the minimum abs difference ; Driver code"
Solution in php:

< ? php function minAbsDiff ( $ n ) { $ left = 1 << ( ( floor ( log ( $ n ) / log ( 2 ) ) ) ) ; $ right = $ left * 2 ; return min ( ( $ n - $ left ) , ( $ right - $ n ) ) ; } $ n = 15 ; echo minAbsDiff ( $ n ) ; ? >


"Minimum absolute difference of a number and its closest prime | Function to check if a number is prime or not ; Function to find the minimum absolute difference between a number and its closest prime ; Variables to store first prime above and below N ; Finding first prime number greater than N ; Finding first prime number less than N ; Variables to store the differences ; Driver code"
Solution in php:

 < ? php function isPrime ( $ N ) { for ( $ i = 2 ; $ i <= sqrt ( $ N ) ; $ i ++ ) { if ( $ N % $ i == 0 ) return false ; } return true ; } function getDifference ( $ N ) { if ( $ N == 0 ) return 2 ; else if ( $ N == 1 ) return 1 ; else if ( isPrime ( $ N ) ) return 0 ; $ aboveN = -1 ; $ belowN = -1 ; $ n1 = $ N + 1 ; while ( true ) { if ( isPrime ( $ n1 ) ) { $ aboveN = $ n1 ; break ; } else $ n1 ++ ; } $ n1 = $ N - 1 ; while ( true ) { if ( isPrime ( $ n1 ) ) { $ belowN = $ n1 ; break ; } else $ n1 -- ; } $ diff1 = $ aboveN - $ N ; $ diff2 = $ N - $ belowN ; return min ( $ diff1 , $ diff2 ) ; } $ N = 25 ; echo getDifference ( $ N ) . "
 " ;


"Minimum absolute difference of adjacent elements in a circular array | PHP program to find maximum difference between adjacent elements in a circular array . ; Checking normal adjacent elements ; Checking circular link ; Driver Code"
Solution in php:

< ? php function minAdjDifference ( $ arr , $ n ) { if ( $ n < 2 ) return ; $ res = abs ( $ arr [ 1 ] - $ arr [ 0 ] ) ; for ( $ i = 2 ; $ i < $ n ; $ i ++ ) $ res = min ( $ res , abs ( $ arr [ $ i ] - $ arr [ $ i - 1 ] ) ) ; $ res = min ( $ res , abs ( $ arr [ $ n - 1 ] - $ arr [ 0 ] ) ) ; echo " Min ▁ Difference ▁ = ▁ " , $ res ; } $ a = array ( 10 , 12 , 13 , 15 , 10 ) ; $ n = count ( $ a ) ; minAdjDifference ( $ a , $ n ) ; ? >


"Minimum adjacent swaps to move maximum and minimum to corners | Function that returns the minimum swaps ; Index of leftmost largest element ; Index of rightmost smallest element ; Driver Code"
Solution in php:


"Minimum and Maximum element of an array which is divisible by a given number k | Function to find the minimum element ; Function to find the maximum element ; Driver code"
Solution in php:

 < ? php function getMin ( $ arr , $ n , $ k ) { $ res = PHP_INT_MAX ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] % $ k == 0 ) $ res = min ( $ res , $ arr [ $ i ] ) ; } return $ res ; } function getMax ( $ arr , $ n , $ k ) { $ res = PHP_INT_MIN ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { if ( $ arr [ $ i ] % $ k == 0 ) $ res = max ( $ res , $ arr [ $ i ] ) ; } return $ res ; } $ arr = array ( 10 , 1230 , 45 , 67 , 1 ) ; $ k = 10 ; $ n = sizeof ( $ arr ) ; echo " Minimum ▁ element ▁ of ▁ array ▁ which ▁ is ▁ " . " divisible ▁ by ▁ k : ▁ " , getMin ( $ arr , $ n , $ k ) , "
 " ; echo " Maximum ▁ element ▁ of ▁ array ▁ which ▁ is ▁ " . " divisible ▁ by ▁ k : ▁ " , getMax ( $ arr , $ n , $ k ) ; ? >


"Minimum and Maximum number of pairs in m teams of n people | PHP program to find minimum and maximum no . of pairs ; Driver code"
Solution in php:

 < ? php function MinimumMaximumPairs ( $ n , $ m ) { $ max_pairs = ( ( $ n - $ m + 1 ) * ( $ n - $ m ) ) / 2 ; $ min_pairs = $ m * ( int ) ( ( ( ( int ) ( $ n - $ m ) / $ m + 1 ) * ( ( int ) ( $ n - $ m ) / $ m ) ) / 2 ) + ( int ) ceil ( ( $ n - $ m ) / $ m ) * ( ( $ n - $ m ) % $ m ) ; echo ( " Minimum ▁ no . ▁ of ▁ pairs ▁ = ▁ " . " $ min _ pairs " . "
 " ) ; echo ( " Maximum ▁ no . ▁ of ▁ pairs ▁ = ▁ " . " $ max _ pairs " ) ; } $ n = 5 ; $ m = 2 ; MinimumMaximumPairs ( $ n , $ m ) ; ? >


"Minimum and maximum number of N chocolates after distribution among K students | Driver code"
Solution in php:


"Minimum array insertions required to make consecutive difference <= K | Function to return minimum number of insertions required ; Initialize insertions to 0 ; return total insertions ; Driver Code"
Solution in php:

< ? php function minInsertions ( $ H , $ n , $ K ) { $ inser = 0 ; for ( $ i = 1 ; $ i < $ n ; ++ $ i ) { $ diff = abs ( $ H [ $ i ] - $ H [ $ i - 1 ] ) ; if ( $ diff <= $ K ) continue ; else $ inser += ceil ( $ diff / $ K ) - 1 ; } return $ inser ; } $ H = array ( 2 , 4 , 8 , 16 ) ; $ K = 3 ; $ n = sizeof ( $ H ) ; echo minInsertions ( $ H , $ n , $ K ) ; ? >


"Minimum boxes required to carry all gifts | Function to return number of boxes ; Sort the boxes in ascending order ; Try to fit smallest box with current heaviest box ( from right side ) ; Driver program"
Solution in php:


"Minimum cells required to reach destination with jumps equal to cell values | function to count minimum cells required to be covered to reach destination ; to store min cells required to be covered to reach a particular cell ; initially no cells can be reached ; base case ; building up the dp [ ] [ ] matrix ; dp [ i ] [ j ] != INT_MAX denotes that cell ( i , j ) can be reached from cell ( 0 , 0 ) and the other half of the condition finds the cell on the right that can be reached from ( i , j ) ; the other half of the condition finds the cell right below that can be reached from ( i , j ) ; it true then cell ( m - 1 , n - 1 ) can be reached from cell ( 0 , 0 ) and returns the minimum number of cells covered ; cell ( m - 1 , n - 1 ) cannot be reached from cell ( 0 , 0 ) ; Driver Code"
Solution in php:


"Minimum changes required such that the string satisfies the given condition | Function to return the minimum changes required ; To store the count of minimum changes , number of ones and the number of zeroes ; First character has to be '1' ; If condition fails changes need to be made ; Return the required count ; Driver code"
Solution in php:

< ? php function minChanges ( $ str , $ n ) { $ count = $ zeros = $ ones = 0 ; if ( $ str [ 0 ] != '1' ) { $ count ++ ; $ ones ++ ; } for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { if ( $ str [ $ i ] == '0' ) $ zeros ++ ; else $ ones ++ ; if ( $ zeros > $ ones ) { $ zeros -- ; $ ones ++ ; $ count ++ ; } } return $ count ; } $ str = "0000" ; $ n = strlen ( $ str ) ; echo minChanges ( $ str , $ n ) ; ? >


"Minimum changes required to make first string substring of second string | Function to find the minimum number of characters to be replaced in string S2 , such that S1 is a substring of S2 ; Get the sizes of both strings ; Traverse the string S2 ; From every index in S2 , check the number of mis - matching characters in substring of length of S1 ; Take minimum of prev and current mis - match ; return answer ; Driver Code"
Solution in php:

< ? php function minimumChar ( $ S1 , $ S2 ) { $ n = strlen ( $ S1 ) ; $ m = strlen ( $ S2 ) ; $ ans = PHP_INT_MAX ; for ( $ i = 0 ; $ i < $ m - $ n + 1 ; $ i ++ ) { $ minRemovedChar = 0 ; for ( $ j = 0 ; $ j < $ n ; $ j ++ ) { if ( $ S1 [ $ j ] != $ S2 [ $ i + $ j ] ) { $ minRemovedChar ++ ; } } $ ans = min ( $ minRemovedChar , $ ans ) ; } return $ ans ; } $ S1 = " abc " ; $ S2 = " paxzk " ; echo minimumChar ( $ S1 , $ S2 ) ; ? >


"Minimum changes to a string to make all substrings distinct | Returns minimum changes to str so that no substring is repeated . ; If length is more than maximum allowed characters , we cannot get the required string . ; Variable to store count of distinct characters ; To store counts of different characters ; Answer is , n - number of distinct char ; Driver Code"
Solution in php:

< ? php function minChanges ( $ str ) { $ n = strlen ( $ str ) ; if ( $ n > 26 ) return -1 ; $ dist_count = 0 ; $ count = array_fill ( 0 , 26 , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ count [ ord ( $ str [ $ i ] ) - 97 ] == 0 ) $ dist_count ++ ; $ count [ ord ( $ str [ $ i ] ) - 97 ] ++ ; } return ( $ n - $ dist_count ) ; } $ str = " aebaecedabbee " ; echo minChanges ( $ str ) ; ? >


"Minimum characters to be replaced to remove the given substring | function to calculate minimum characters to replace ; mismatch occurs ; if all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; Driver Code"
Solution in php:

< ? php function replace ( $ A , $ B ) { $ n = strlen ( $ A ) ; $ m = strlen ( $ B ) ; $ count = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { for ( $ j = 0 ; $ j < $ m ; $ j ++ ) { if ( $ i + $ j >= $ n ) { break ; } else if ( $ A [ $ i + $ j ] != $ B [ $ j ] ) { break ; } } if ( $ j == $ m ) { $ count ++ ; $ i = $ i + $ m - 1 ; } } return $ count ; } $ str1 = " aaaaaaaa " ; $ str2 = " aaa " ; echo ( replace ( $ str1 , $ str2 ) ) ; ? >


"Minimum cost for acquiring all coins with k extra coins allowed with every coin | Converts coin [ ] to prefix sum array ; sort the coins value ; Maintain prefix sum array ; Function to calculate min cost when we can get k extra coins after paying cost of one . ; calculate no . of coins needed ; return sum of from prefix array ; Driver Code"
Solution in php:

 < ? php function preprocess ( & $ coin , $ n ) { sort ( $ coin ) ; for ( $ i = 1 ; $ i <= $ n - 1 ; $ i ++ ) $ coin [ $ i ] += $ coin [ $ i - 1 ] ; } function minCost ( & $ coin , $ n , $ k ) { $ coins_needed = ceil ( 1.0 * $ n / ( $ k + 1 ) ) ; return $ coin [ $ coins_needed - 1 ] ; } $ coin = array ( 8 , 5 , 3 , 10 , 2 , 1 , 15 , 25 ) ; $ n = sizeof ( $ coin ) ; preprocess ( $ coin , $ n ) ; $ k = 3 ; echo minCost ( $ coin , $ n , $ k ) . "
 " ; $ k = 7 ; echo minCost ( $ coin , $ n , $ k ) . "
 " ; ? >


"Minimum cost for acquiring all coins with k extra coins allowed with every coin | function to calculate min cost ; sort the coins value ; calculate no . of coins needed ; calculate sum of all selected coins ; Driver Code"
Solution in php:

< ? php function minCost ( $ coin , $ n , $ k ) { sort ( $ coin ) ; sort ( $ coin , $ n ) ; $ coins_needed = ceil ( 1.0 * $ n / ( $ k + 1 ) ) ; $ ans = 0 ; for ( $ i = 0 ; $ i <= $ coins_needed - 1 ; $ i ++ ) $ ans += $ coin [ $ i ] ; return $ ans ; } { $ coin = array ( 8 , 5 , 3 , 10 , 2 , 1 , 15 , 25 ) ; $ n = sizeof ( $ coin ) / sizeof ( $ coin [ 0 ] ) ; $ k = 3 ; echo minCost ( $ coin , $ n , $ k ) ; return 0 ; } ? >


"Minimum cost to convert string into palindrome | Function to return cost ; length of string ; Iterate from both sides of string . If not equal , a cost will be there ; Driver code"
Solution in php:

< ? php function cost ( $ str ) { $ len = strlen ( $ str ) ; $ res = 0 ; for ( $ i = 0 , $ j = $ len - 1 ; $ i < $ j ; $ i ++ , $ j -- ) if ( $ str [ $ i ] != $ str [ $ j ] ) $ res += ( min ( ord ( $ str [ $ i ] ) , ord ( $ str [ $ j ] ) ) - ord ( ' a ' ) + 1 ) ; return $ res ; } $ str = " abcdef " ; echo cost ( $ str ) ; ? >


"Minimum cost to fill given weight in a bag | PHP program to find minimum cost to get exactly W Kg with given packets ; cost [ ] initial cost array including unavailable packet W capacity of bag ; val [ ] and wt [ ] arrays val [ ] array to store cost of ' i ' kg packet of orange wt [ ] array weight of packet of orange ; traverse the original cost [ ] array and skip unavailable packets and make val [ ] and wt [ ] array . size variable tells the available number of distinct weighted packets ; fill 0 th row with infinity ; fill 0 'th column with 0 ; now check for each weight one by one and fill the matrix according to the condition ; wt [ i - 1 ] > j means capacity of bag is less then weight of item ; here we check we get minimum cost either by including it or excluding it ; exactly weight W can not be made by given weights ; Driver Code"
Solution in php:

< ? php $ INF = 1000000 ; function MinimumCost ( & $ cost , $ n , $ W ) { global $ INF ; $ val = array ( ) ; $ wt = array ( ) ; $ size = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) { if ( $ cost [ $ i ] != -1 ) { array_push ( $ val , $ cost [ $ i ] ) ; array_push ( $ wt , $ i + 1 ) ; $ size ++ ; } } $ n = $ size ; $ min_cost = array_fill ( 0 , $ n + 1 , array_fill ( 0 , $ W + 1 , NULL ) ) ; for ( $ i = 0 ; $ i <= $ W ; $ i ++ ) $ min_cost [ 0 ] [ $ i ] = $ INF ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) $ min_cost [ $ i ] [ 0 ] = 0 ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { for ( $ j = 1 ; $ j <= $ W ; $ j ++ ) { if ( $ wt [ $ i - 1 ] > $ j ) $ min_cost [ $ i ] [ $ j ] = $ min_cost [ $ i - 1 ] [ $ j ] ; else $ min_cost [ $ i ] [ $ j ] = min ( $ min_cost [ $ i - 1 ] [ $ j ] , $ min_cost [ $ i ] [ $ j - $ wt [ $ i - 1 ] ] + $ val [ $ i - 1 ] ) ; } } if ( $ min_cost [ $ n ] [ $ W ] == $ INF ) return -1 ; else return $ min_cost [ $ n ] [ $ W ] ; } $ cost = array ( 1 , 2 , 3 , 4 , 5 ) ; $ W = 5 ; $ n = sizeof ( $ cost ) ; echo MinimumCost ( $ cost , $ n , $ W ) ; ? >


"Minimum cost to form a number X by adding up powers of 2 | Function to return the minimum cost ; Re - compute the array ; Add answers for set bits ; If bit is set ; Increase the counter ; Right shift the number ; Driver code"
Solution in php:


"Minimum cost to make array size 1 by removing larger of pairs | function to calculate the minimum cost ; Minimum cost is n - 1 multiplied with minimum element . ; Driver Code"
Solution in php:

< ? php function cost ( $ a , $ n ) { return ( $ n - 1 ) * ( min ( $ a ) ) ; } $ a = array ( 4 , 3 , 2 ) ; $ n = count ( $ a ) ; echo cost ( $ a , $ n ) ; ? >


"Minimum cost to make two strings identical by deleting the digits | Function to returns cost of removing the identical characters in LCS for X [ 0. . m - 1 ] , Y [ 0. . n - 1 ] ; Following steps build L [ m + 1 ] [ n + 1 ] in bottom up fashion . Note that L [ i ] [ j ] contains cost of removing identical characters in LCS of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] ; If both characters are same , add both of them ; Otherwise find the maximum cost among them ; Returns cost of making X [ ] and Y [ ] identical ; Find LCS of X [ ] and Y [ ] ; Initialize the cost variable ; Find cost of all characters in both strings ; Driver code"
Solution in php: