codeparrot/xlcost-text-to-code huggingface dataset:
Maximize product of array by replacing array elements with its sum or product with element from another array | Java program for the above approach ; Function to find the largest product of array A [ ] ; Base Case ; Store all the elements of the array A [ ] ; Sort the Array B [ ] ; Traverse the array B [ ] ; Pop minimum element ; Check which operation is producing maximum element ; Insert resultant element into the priority queue ; Evaluate the product of the elements of A [ ] ; Return the maximum product ; Driver Code ; Given arrays ; Function Call
import java . io . * ; import java . util . * ; class GFG { public static int largeProduct ( int A [ ] , int B [ ] , int N ) { if ( N == 0 ) return 0 ; PriorityQueue < Integer > pq = new PriorityQueue < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) pq . add ( A [ i ] ) ; Arrays . sort ( B ) ; for ( int i = 0 ; i < N ; i ++ ) { int minn = pq . poll ( ) ; int maximized_element = Math . max ( minn * B [ i ] , minn + B [ i ] ) ; pq . add ( maximized_element ) ; } int max_product = 1 ; while ( pq . size ( ) > 0 ) { max_product *= pq . poll ( ) ; } return max_product ; } public static void main ( String [ ] args ) { int A [ ] = { 1 , 1 , 10 } ; int B [ ] = { 1 , 1 , 1 } ; int N = 3 ; System . out . println ( largeProduct ( A , B , N ) ) ; } }
Print all root to leaf paths with there relative positions | Java program to print all root to leaf paths with there relative position ; tree structure ; Function create new node ; Store path information ; Prints given root to leaf path with underscores ; Find the minimum horizontal distance value in current root to leaf path ; Find minimum horizontal distance ; Print the root to leaf path with " _ " that indicate the related position ; Current tree node ; Print underscore ; Print current key ; A utility function print all path from root to leaf working of this function is similar to function of " Print _ vertical _ order " : Print paths of binary tree in vertical order www . geeksforgeeks . org / print - binary - tree - vertical - order - set - 2 / https : ; Base case ; Leaf node ; Add leaf node and then print path ; Store current path information ; Call left sub_tree ; Call left sub_tree ; Base case ; Driver code
import java . util . ArrayList ; class Graph { static final int MAX_PATH_SIZE = 1000 ; static class Node { char data ; Node left , right ; } ; static Node newNode ( char data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } static class PATH { int Hd ; char key ; public PATH ( int Hd , char key ) { this . Hd = Hd ; this . key = key ; } public PATH ( ) { } } ; static void printPath ( ArrayList < PATH > path , int size ) { int minimum_Hd = Integer . MAX_VALUE ; PATH p ; for ( int it = 0 ; it < size ; it ++ ) { p = path . get ( it ) ; minimum_Hd = Math . min ( minimum_Hd , p . Hd ) ; } for ( int it = 0 ; it < size ; it ++ ) { p = path . get ( it ) ; int noOfUnderScores = Math . abs ( p . Hd - minimum_Hd ) ; for ( int i = 0 ; i < noOfUnderScores ; i ++ ) System . out . print ( " _ " ) ; System . out . println ( p . key ) ; } System . out . println ( " = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = " ) ; } static void printAllPathsUtil ( Node root , ArrayList < PATH > AllPath , int HD , int order ) { if ( root == null ) return ; if ( root . left == null && root . right == null ) { AllPath . set ( order , new PATH ( HD , root . data ) ) ; printPath ( AllPath , order + 1 ) ; return ; } AllPath . set ( order , new PATH ( HD , root . data ) ) ; printAllPathsUtil ( root . left , AllPath , HD - 1 , order + 1 ) ; printAllPathsUtil ( root . right , AllPath , HD + 1 , order + 1 ) ; } static void printAllPaths ( Node root ) { if ( root == null ) return ; ArrayList < PATH > Allpaths = new ArrayList < > ( ) ; for ( int i = 0 ; i < MAX_PATH_SIZE ; i ++ ) { Allpaths . add ( new PATH ( ) ) ; } printAllPathsUtil ( root , Allpaths , 0 , 0 ) ; } public static void main ( String [ ] args ) { Node root = newNode ( ' A ' ) ; root . left = newNode ( ' B ' ) ; root . right = newNode ( ' C ' ) ; root . left . left = newNode ( ' D ' ) ; root . left . right = newNode ( ' E ' ) ; root . right . left = newNode ( ' F ' ) ; root . right . right = newNode ( ' G ' ) ; printAllPaths ( root ) ; } }
Minimum steps required to rearrange given array to a power sequence of 2 | Java Program to implement the above approach ; Function to calculate the minimum steps required to convert given array into a power sequence of 2 ; Sort the array in ascending order ; Calculate the absolute difference between arr [ i ] and 2 ^ i for each index ; Return the answer ; Driver Code
import java . util . * ; import java . lang . Math ; class GFG { static int minsteps ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += Math . abs ( arr [ i ] - Math . pow ( 2 , i ) ) ; } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 8 , 2 , 10 , 6 } ; int n = arr . length ; System . out . println ( minsteps ( arr , n ) ) ; } }
Block swap algorithm for array rotation |  ; Wrapper over the recursive function leftRotateRec ( ) It left rotates arr [ ] by d . ; Return If number of elements to be rotated is zero or equal to array size ; If number of elements to be rotated is exactly half of array size ; If A is shorter ; If B is shorter ; function to print an array ; This function swaps d elements starting at index fi with d elements starting at index si ; Driver Code
import java . util . * ; class GFG { public static void leftRotate ( int arr [ ] , int d , int n ) { leftRotateRec ( arr , 0 , d , n ) ; } public static void leftRotateRec ( int arr [ ] , int i , int d , int n ) { if ( d == 0 d == n ) return ; if ( n - d == d ) { swap ( arr , i , n - d + i , d ) ; return ; } if ( d < n - d ) { swap ( arr , i , n - d + i , d ) ; leftRotateRec ( arr , i , d , n - d ) ; } else { swap ( arr , i , d , n - d ) ; leftRotateRec ( arr , n - d + i , 2 * d - n , d ) ; } } public static void printArray ( int arr [ ] , int size ) { int i ; for ( i = 0 ; i < size ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; System . out . println ( ) ; } public static void swap ( int arr [ ] , int fi , int si , int d ) { int i , temp ; for ( i = 0 ; i < d ; i ++ ) { temp = arr [ fi + i ] ; arr [ fi + i ] = arr [ si + i ] ; arr [ si + i ] = temp ; } } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; leftRotate ( arr , 2 , 7 ) ; printArray ( arr , 7 ) ; } }
Cost required to empty a given array by repeated removal of maximum obtained by given operations | Java program for the above approach ; Function to find the total cost of removing all array elements ; Sort the array in descending order ; Stores the total cost ; Contribution of i - th greatest element to the cost ; Remove the element ; If negative ; Add to the final cost ; Return the cost ; Driver Code ; Given array arr [ ] ; Function Call
import java . util . * ; class GFG { static int findCost ( Integer [ ] a , int n ) { Arrays . sort ( a , Collections . reverseOrder ( ) ) ; int count = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int p = a [ j ] - j ; a [ j ] = 0 ; if ( p < 0 ) { p = 0 ; continue ; } count += p ; } return count ; } public static void main ( String [ ] args ) { Integer arr [ ] = { 1 , 6 , 7 , 4 , 2 , 5 , 3 } ; int N = arr . length ; System . out . print ( findCost ( arr , N ) ) ; } }
Block swap algorithm for array rotation | Java code for above implementation ; A is shorter ; B is shorter ; Finally , block swap A and B
static void leftRotate ( int arr [ ] , int d , int n ) { int i , j ; if ( d == 0 d == n ) return ; i = d ; j = n - d ; while ( i != j ) { if ( i < j ) { swap ( arr , d - i , d + j - i , i ) ; j -= i ; } else { swap ( arr , d - i , d , j ) ; i -= j ; } } swap ( arr , d - i , d , i ) ; }
Count of index pairs with equal elements in an array | Set 2 | Java program for the above approach ; Function that count the pairs having same elements in the array arr [ ] ; Hash map to keep track of occurences of elements ; Traverse the array arr [ ] ; Check if occurence of arr [ i ] > 0 add count [ arr [ i ] ] to answer ; Return the result ; Driver Code ; Given array arr [ ] ; Function call
import java . util . * ; class GFG { static int countPairs ( int arr [ ] , int n ) { int ans = 0 ; HashMap < Integer , Integer > count = new HashMap < > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( count . containsKey ( arr [ i ] ) ) { ans += count . get ( arr [ i ] ) ; count . put ( arr [ i ] , count . get ( arr [ i ] ) + 1 ) ; } else { count . put ( arr [ i ] , 1 ) ; } } return ans ; } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 1 , 1 } ; int N = arr . length ; System . out . print ( countPairs ( arr , N ) ) ; } }
Maximize shortest path between given vertices by adding a single edge | Java program for the above approach ; To store graph as adjacency list ; To store the shortest path ; Function that performs BFS Traversal ; Fill initially each distance as INF ; Perform BFS ; Traverse the current edges ; Update the distance ; Insert in queue ; Function that maximizes the shortest path between source and destination vertex by adding a single edge between given selected nodes ; To update the shortest distance between node 1 to other vertices ; To update the shortest distance between node N to other vertices ; Store the values x [ i ] - y [ i ] ; Sort all the vectors of pairs ; Traverse data [ ] ; Maximize x [ a ] - y [ b ] ; Print minimum cost ; Driver code ; Given nodes and edges ; Sort the selected nodes ; Given edges ; Function Call
import java . util . * ; import java . lang . * ; class GFG { static int INF = ( int ) 1e9 + 7 ; static int N , M ; static ArrayList < ArrayList < Integer > > edges ; static int [ ] [ ] dist = new int [ 2 ] [ 200000 ] ; static void bfs ( int [ ] dist , int s ) { int [ ] q = new int [ 200000 ] ; Arrays . fill ( dist , INF ) ; int qh = 0 , qt = 0 ; q [ qh ++ ] = s ; dist [ s ] = 0 ; while ( qt < qh ) { int x = q [ qt ++ ] ; for ( Integer y : edges . get ( x ) ) { if ( dist [ y ] == INF ) { dist [ y ] = dist [ x ] + 1 ; q [ qh ++ ] = y ; } } } } static void shortestPathCost ( int selected [ ] , int K ) { ArrayList < int [ ] > data = new ArrayList < > ( ) ; bfs ( dist [ 0 ] , 0 ) ; bfs ( dist [ 1 ] , N - 1 ) ; for ( int i = 0 ; i < K ; i ++ ) { data . add ( new int [ ] { dist [ 0 ] [ selected [ i ] ] - dist [ 1 ] [ selected [ i ] ] , selected [ i ] } ) ; } Collections . sort ( data , ( a , b ) -> a [ 0 ] - b [ 0 ] ) ; int best = 0 ; int MAX = - INF ; for ( int [ ] it : data ) { int a = it [ 1 ] ; best = Math . max ( best , MAX + dist [ 1 ] [ a ] ) ; MAX = Math . max ( MAX , dist [ 0 ] [ a ] ) ; } System . out . println ( Math . min ( dist [ 0 ] [ N - 1 ] , best + 1 ) ) ; } public static void main ( String [ ] args ) { N = 5 ; M = 4 ; int K = 2 ; int selected [ ] = { 1 , 3 } ; Arrays . sort ( selected ) ; edges = new ArrayList < > ( ) ; for ( int i = 0 ; i < 200005 ; i ++ ) edges . add ( new ArrayList < Integer > ( ) ) ; edges . get ( 0 ) . add ( 1 ) ; edges . get ( 1 ) . add ( 0 ) ; edges . get ( 1 ) . add ( 2 ) ; edges . get ( 2 ) . add ( 1 ) ; edges . get ( 2 ) . add ( 3 ) ; edges . get ( 3 ) . add ( 2 ) ; edges . get ( 3 ) . add ( 4 ) ; edges . get ( 4 ) . add ( 3 ) ; shortestPathCost ( selected , K ) ; } }
Program to cyclically rotate an array by one |  ; i and j pointing to first and last element respectively ; Driver program
import java . util . Arrays ; public class Test { static int arr [ ] = new int [ ] { 1 , 2 , 3 , 4 , 5 } ; static void rotate ( ) { int i = 0 , j = arr . length - 1 ; while ( i != j ) { int temp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = temp ; i ++ ; } } public static void main ( String [ ] args ) { System . out . println ( " Given ▁ Array ▁ is " ) ; System . out . println ( Arrays . toString ( arr ) ) ; rotate ( ) ; System . out . println ( " Rotated ▁ Array ▁ is " ) ; System . out . println ( Arrays . toString ( arr ) ) ; } }
Minimum cost to empty Array where cost of removing an element is 2 ^ ( removed_count ) * arr [ i ] | Java implementation to find the minimum cost of removing all elements from the array ; Reverse array in decreasing order ; Function to find the minimum cost of removing elements from the array ; Sorting in Increasing order ; Loop to find the minimum cost of removing elements ; Driver Code ; Function call
import java . util . * ; class GFG { static long [ ] reverse ( long a [ ] ) { int i , n = a . length ; long t ; for ( i = 0 ; i < n / 2 ; i ++ ) { t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } return a ; } static long removeElements ( long arr [ ] , int n ) { Arrays . sort ( arr ) ; arr = reverse ( arr ) ; long ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += arr [ i ] * Math . pow ( 2 , i ) ; } return ans ; } public static void main ( String [ ] args ) { int n = 4 ; long arr [ ] = { 3 , 1 , 2 , 3 } ; System . out . print ( removeElements ( arr , n ) ) ; } }
Flattening a linked list | Set 2 | Java program for Flattening a linked list using Heaps ; Linked list Node ; Function to print the linked list ; Class that compares the value pointed by node and make LinkedList sorted ; Function which returns the root of the flattened linked list ; Min Heap which will return smallest element currently present in heap ; Push the head nodes of each downward linked list ; This loop will execute till the pq becomes empty ; Pop out the node that contains element currently in heap ; Push the next node pointed by the current node into heap if it is not null ; Create new linked list that is to be returned ; Pointer to head node in the linked list ; Create and push new nodes ; Driver code ; Flatten the list ; Print the flattened linked list
import java . util . * ; class Node { int data ; Node right , down ; Node ( int data ) { this . data = data ; right = null ; down = null ; } } class pair { int val ; Node head ; pair ( Node head , int val ) { this . val = val ; this . head = head ; } } public static void printList ( Node h ) { while ( h != null ) { System . out . print ( h . data + " ▁ " ) ; h = h . down ; } } class pairComp implements Comparator < pair > { public int compare ( pair p1 , pair p2 ) { return p1 . val - p2 . val ; } } class GFG { public static Node flatten ( Node root ) { Node ptr = root ; Node h = null ; PriorityQueue < pair > pq = new PriorityQueue < pair > ( new pairComp ( ) ) ; while ( ptr != null ) { pq . add ( new pair ( ptr , ptr . data ) ) ; ptr = ptr . right ; } while ( ! pq . isEmpty ( ) ) { Node temp = pq . poll ( ) . head ; if ( temp . down != null ) { pq . add ( new pair ( temp . down , temp . down . data ) ) ; } if ( h == null ) { h = temp ; ptr = temp ; ptr . right = null ; } else { ptr . down = temp ; ptr = temp ; ptr . right = null ; } } return h ; } public static Node push ( Node head_ref , int data ) { Node new_node = new Node ( data ) ; new_node . down = head_ref ; head_ref = new_node ; return head_ref ; } public static void main ( String args [ ] ) { Node head = null ; head = push ( head , 30 ) ; head = push ( head , 8 ) ; head = push ( head , 7 ) ; head = push ( head , 5 ) ; head . right = push ( head . right , 20 ) ; head . right = push ( head . right , 10 ) ; head . right . right = push ( head . right . right , 50 ) ; head . right . right = push ( head . right . right , 22 ) ; head . right . right = push ( head . right . right , 19 ) ; head . right . right . right = push ( head . right . right . right , 45 ) ; head . right . right . right = push ( head . right . right . right , 40 ) ; head . right . right . right = push ( head . right . right . right , 35 ) ; head . right . right . right = push ( head . right . right . right , 20 ) ; head = flatten ( head ) ; printList ( head ) ; } }
Lexicographically largest string possible in one swap | Java implementation to find the lexicographically largest string by atmost at most one swap ; Function to return the lexicographically largest string possible by swapping at most one character ; Stores last occurrence of every character ; Initialize with - 1 for every character ; Keep updating the last occurrence of each character ; If a previously unvisited character occurs ; Stores the sorted string ; Character to replace ; Find the last occurrence of this character ; Swap this with the last occurrence ; Function to reverse array ; Driver Code
import java . util . * ; import java . lang . * ; class GFG { static String findLargest ( StringBuilder s ) { int len = s . length ( ) ; int [ ] loccur = new int [ 26 ] ; Arrays . fill ( loccur , - 1 ) ; for ( int i = len - 1 ; i >= 0 ; -- i ) { int chI = s . charAt ( i ) - ' a ' ; if ( loccur [ chI ] == - 1 ) { loccur [ chI ] = i ; } } char [ ] sorted_s = s . toString ( ) . toCharArray ( ) ; Arrays . sort ( sorted_s ) ; reverse ( sorted_s ) ; for ( int i = 0 ; i < len ; ++ i ) { if ( s . charAt ( i ) != sorted_s [ i ] ) { int chI = sorted_s [ i ] - ' a ' ; int last_occ = loccur [ chI ] ; char tmp = s . charAt ( i ) ; s . setCharAt ( i , s . charAt ( last_occ ) ) ; s . setCharAt ( last_occ , tmp ) ; break ; } } return s . toString ( ) ; } static void reverse ( char a [ ] ) { int i , n = a . length ; for ( i = 0 ; i < n / 2 ; i ++ ) { char t = a [ i ] ; a [ i ] = a [ n - i - 1 ] ; a [ n - i - 1 ] = t ; } } public static void main ( String [ ] args ) { StringBuilder s = new StringBuilder ( " yrstvw " ) ; System . out . println ( findLargest ( s ) ) ; } }
Given a sorted and rotated array , find if there is a pair with a given sum | Java program to find a pair with a given sum in a sorted and rotated array ; This function returns true if arr [ 0. . n - 1 ] has a pair with sum equals to x . ; Find the pivot element ; l is now index of ; smallest element r is now index of largest ; element Keep moving either l or r till they meet ; If we find a pair with sum x , we return true ; If current pair sum is less , move to the higher sum ; Move to the lower sum side ; Driver program to test above function
class PairInSortedRotated { static boolean pairInSortedRotated ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) return true ; if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return false ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 15 , 6 , 8 , 9 , 10 } ; int sum = 16 ; int n = arr . length ; if ( pairInSortedRotated ( arr , n , sum ) ) System . out . print ( " Array ▁ has ▁ two ▁ elements " + " ▁ with ▁ sum ▁ 16" ) ; else System . out . print ( " Array ▁ doesn ' t ▁ have ▁ two " + " ▁ elements ▁ with ▁ sum ▁ 16 ▁ " ) ; } }
Given a sorted and rotated array , find if there is a pair with a given sum | Java program to find number of pairs with a given sum in a sorted and rotated array . ; This function returns count of number of pairs with sum equals to x . ; Find the pivot element . Pivot element is largest element of array . ; l is index of smallest element . ; r is index of largest element . ; Variable to store count of number of pairs . ; Find sum of pair formed by arr [ l ] and arr [ r ] and update l , r and cnt accordingly . ; If we find a pair with sum x , then increment cnt , move l and r to next element . ; This condition is required to be checked , otherwise l and r will cross each other and loop will never terminate . ; If current pair sum is less , move to the higher sum side . ; If current pair sum is greater , move to the lower sum side . ; Driver Code
import java . io . * ; class GFG { static int pairsInSortedRotated ( int arr [ ] , int n , int x ) { int i ; for ( i = 0 ; i < n - 1 ; i ++ ) if ( arr [ i ] > arr [ i + 1 ] ) break ; int l = ( i + 1 ) % n ; int r = i ; int cnt = 0 ; while ( l != r ) { if ( arr [ l ] + arr [ r ] == x ) { cnt ++ ; if ( l == ( r - 1 + n ) % n ) { return cnt ; } l = ( l + 1 ) % n ; r = ( r - 1 + n ) % n ; } else if ( arr [ l ] + arr [ r ] < x ) l = ( l + 1 ) % n ; else r = ( n + r - 1 ) % n ; } return cnt ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 15 , 6 , 7 , 9 , 10 } ; int sum = 16 ; int n = arr . length ; System . out . println ( pairsInSortedRotated ( arr , n , sum ) ) ; } }
Find maximum value of Sum ( i * arr [ i ] ) with only rotations on given array allowed | Java program to find max value of i * arr [ i ] ; Returns max possible value of i * arr [ i ] ; Find array sum and i * arr [ i ] with no rotation Stores sum of arr [ i ] ; Stores sum of i * arr [ i ] ; Initialize result as 0 rotation sum ; Try all rotations one by one and find the maximum rotation sum . ; Return result ; Driver method to test the above function
import java . util . Arrays ; class Test { static int arr [ ] = new int [ ] { 10 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; static int maxSum ( ) { int arrSum = 0 ; int currVal = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { arrSum = arrSum + arr [ i ] ; currVal = currVal + ( i * arr [ i ] ) ; } int maxVal = currVal ; for ( int j = 1 ; j < arr . length ; j ++ ) { currVal = currVal + arrSum - arr . length * arr [ arr . length - j ] ; if ( currVal > maxVal ) maxVal = currVal ; } return maxVal ; } public static void main ( String [ ] args ) { System . out . println ( " Max ▁ sum ▁ is ▁ " + maxSum ( ) ) ; } }
Print the nodes at odd levels of a tree | Recursive Java program to print odd level nodes ; If empty tree ; If current node is of odd level ; Recur for children with isOdd switched . ; Utility method to create a node ; Driver code
class GfG { static class Node { int data ; Node left , right ; } static void printOddNodes ( Node root , boolean isOdd ) { if ( root == null ) return ; if ( isOdd == true ) System . out . print ( root . data + " ▁ " ) ; printOddNodes ( root . left , ! isOdd ) ; printOddNodes ( root . right , ! isOdd ) ; } static Node newNode ( int data ) { Node node = new Node ( ) ; node . data = data ; node . left = null ; node . right = null ; return ( node ) ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; printOddNodes ( root , true ) ; } }
Maximum sum of i * arr [ i ] among all rotations of a given array | A Naive Java program to find maximum sum rotation ; 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 rotation the array, but compute  sum by finding ndexes when arr[i] is  first element ; Update result if required ; Driver code
import java . util . * ; import java . io . * ; class GFG { static int maxSum ( int arr [ ] , int n ) { int res = Integer . MIN_VALUE ; for ( int i = 0 ; i < n ; i ++ ) { int curr_sum = 0 ; for ( int j = 0 ; j < n ; j ++ ) { int index = ( i + j ) % n ; curr_sum += j * arr [ index ] ; } res = Math . max ( res , curr_sum ) ; } return res ; } public static void main ( String args [ ] ) { int arr [ ] = { 8 , 3 , 1 , 2 } ; int n = arr . length ; System . out . println ( maxSum ( arr , n ) ) ; } }
Maximum sum of i * arr [ i ] among all rotations of a given array | An efficient Java 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
import java . io . * ; class GFG { static int maxSum ( int arr [ ] , int n ) { int cum_sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) cum_sum += arr [ i ] ; int curr_val = 0 ; for ( int i = 0 ; i < n ; i ++ ) curr_val += i * arr [ i ] ; int res = curr_val ; for ( int i = 1 ; i < n ; i ++ ) { int next_val = curr_val - ( cum_sum - arr [ i - 1 ] ) + arr [ i - 1 ] * ( n - 1 ) ; curr_val = next_val ; res = Math . max ( res , next_val ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { 8 , 3 , 1 , 2 } ; int n = arr . length ; System . out . println ( maxSum ( arr , n ) ) ; } }