The Wayback Machine - https://web.archive.org/web/20240818163937/https://www.geeksforgeeks.org/find-maximum-value-of-sum-iarri-with-only-rotations-on-given-array-allowed/
Open In App

Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[] of size N, the task is to find the maximum possible sum of i*arr[i] when the array can be rotated any number of times.

Examples :  

Input: arr[] = {1, 20, 2, 10}
Output: 72.We can get 72 by rotating array twice.
{2, 10, 1, 20}
20*3 + 1*2 + 10*1 + 2*0 = 72

Input: arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9}
Output: 330
We can get 330 by rotating array 9 times.
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
0*1 + 1*2 + 2*3 … 9*10 = 330

Naive Approach: The basic idea of this approach is 

Find all rotations one by one, check the sum of every rotation and return the maximum sum. 

Algorithm

  • Start by initializing max_sum to INT_MIN
  • Loop say i,from 0 to n-1:
    • a. Initialize sum to 0
    • b. Loop j from 0 to n-1:
      • i. Calculate the index of the j-th element after rotation: (i+j) % n
      • ii. Add the product of the element and its index to sum: j * arr[(i+j) % n]
    • c. If sum is greater than max_sum, update max_sum to sum
  • Return max_sum

C++




#include <climits>
#include <iostream>
 
using namespace std;
 
int max_sum_rotation(int arr[], int n)
{
    int max_sum = INT_MIN; // set the maximum sum to the
                           // minimum possible value
    for (int i = 0; i < n;
         i++) { // loop through all possible rotations
        int sum = 0; // set the current sum to zero
        for (int j = 0; j < n;
             j++) { // loop through all elements in the
                    // array
            int index
                = (i + j)
                  % n; // calculate the index of the current
                       // element after rotation
            sum += j * arr[index]; // add the product of the
                                   // element with its index
                                   // to the sum
        }
        max_sum = max(
            max_sum,
            sum); // update the maximum sum if necessary
    }
    return max_sum; // return the maximum sum obtained over
                    // all rotations
}
 
int main()
{
    int arr[] = {
        10, 1, 2, 3, 4, 5, 6, 7, 8, 9
    }; // define an array
    int n = sizeof(arr)
            / sizeof(
                arr[0]); // calculate the size of the array
    cout << max_sum_rotation(arr, n)
         << endl; // call the function and print the result
    return 0; // indicate successful program completion
}


Java




/*package whatever //do not write package name here */
 
import java.io.*;
public class MaxSumRotation {
    public static int maxSumRotation(int[] arr, int n) {
        // Set the maximum sum to the minimum possible value
        int maxSum = Integer.MIN_VALUE;
 
        // Loop through all possible rotations
        for (int i = 0; i < n; i++) {
            // Set the current sum to zero
            int sum = 0;
 
            // Loop through all elements in the array
            for (int j = 0; j < n; j++) {
                // Calculate the index of the current element after rotation
                int index = (i + j) % n;
 
                // Add the product of the element with its index to the sum
                sum += j * arr[index];
            }
 
            // Update the maximum sum if necessary
            maxSum = Math.max(maxSum, sum);
        }
 
        // Return the maximum sum obtained over all rotations
        return maxSum;
    }
 
    public static void main(String[] args) {
        int[] arr = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int n = arr.length;
        System.out.println(maxSumRotation(arr, n));
    }
}


Python3




def max_sum_rotation(arr, n):
    # set the maximum sum to the
    # minimum possible value
    max_sum = float('-inf')
     
     
    # loop through all possible rotations
    for i in range(n):
       
        # set the current sum to zero
        sum = 0
         
        # loop through all elements in the array
        for j in range(n):
            # calculate the index of the current element after rotation
            index = (i + j) % n
             
            # add the product of the element with its index to the sum
            sum += j * arr[index]
         
        # update the maximum sum if necessary
        max_sum = max(max_sum, sum)
     
    # return the maximum sum obtained over all rotations
    return max_sum
# Test case
arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
n = len(arr)
print(max_sum_rotation(arr, n))


C#




using System;
 
class Program
{
    static int MaxSumRotation(int[] arr, int n)
    {
        int maxSum = int.MinValue; // set the maximum sum to the minimum possible value
 
        for (int i = 0; i < n; i++)
        {
            int sum = 0; // set the current sum to zero
 
            for (int j = 0; j < n; j++)
            {
                int index = (i + j) % n; // calculate the index of the current element after rotation
                sum += j * arr[index]; // add the product of the element with its index to the sum
            }
 
            maxSum = Math.Max(maxSum, sum); // update the maximum sum if necessary
        }
 
        return maxSum; // return the maximum sum obtained over all rotations
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // define an array
        int n = arr.Length; // calculate the size of the array
 
        Console.WriteLine(MaxSumRotation(arr, n)); // call the function and print the result
    }
}


Javascript




function maxSumRotation(arr) {
    const n = arr.length;
    let maxSum = Number.MIN_SAFE_INTEGER;
 
    for (let i = 0; i < n; i++) {
        let sum = 0;
 
        for (let j = 0; j < n; j++) {
            const index = (i + j) % n;
            sum += j * arr[index];
        }
 
        maxSum = Math.max(maxSum, sum);
    }
    return maxSum;
}
const arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(maxSumRotation(arr));


Output

330









Time Complexity: O(N2), where n is the size of the input array. 
Auxiliary Space: O(1), because it uses a constant amount of extra space to store the variables max_sum, sum, i, and j. 

Efficient Approach: The idea is as follows:

Let Rj be value of i*arr[i] with j rotations. 

  • The idea is to calculate the next rotation value from the previous rotation, i.e., calculate Rj from Rj-1. 
  • We can calculate the initial value of the result as R0, then keep calculating the next rotation values. 

How to efficiently calculate Rj from Rj-1? 

This can be done in O(1) time. Below are the details. 

Let us calculate initial value of i*arr[i] with no rotation
R0 = 0*arr[0] + 1*arr[1] +…+ (n-1)*arr[n-1]

After 1 rotation arr[n-1], becomes first element of array, 

  • arr[0] becomes second element, arr[1] becomes third element and so on.
  • R1 = 0*arr[n-1] + 1*arr[0] +…+ (n-1)*arr[n-2]
  • R1 – R0 = arr[0] + arr[1] + … + arr[n-2] – (n-1)*arr[n-1]

After 2 rotations arr[n-2], becomes first element of array, 

  • arr[n-1] becomes second element, arr[0] becomes third element and so on.
  • R2 = 0*arr[n-2] + 1*arr[n-1] +…+ (n-1)*arr[n-3]
  • R2 – R1 = arr[0] + arr[1] + … + arr[n-3] – (n-1)*arr[n-2] + arr[n-1]

If we take a closer look at above values, we can observe below pattern
Rj – Rj-1 = arrSum – n * arr[n-j],
Where arrSum is sum of all array elements, i.e.,  arrSum = ∑ arr[i] , 0 ≤ i ≤ N-1

Follow the below illustration for a better understanding. 

Illustration:

Given arr[]={10, 1, 2, 3, 4, 5, 6, 7, 8, 9}, 

arrSum = 55, currVal = summation of (i*arr[i]) =  285
In each iteration the currVal is currVal = currVal + arrSum-n*arr[n-j] ,

1st rotation: currVal = 285 + 55 –  (10 *  9) =  250

2nd rotation: currVal = 250 + 55 – (10 * 8) = 225

3rd rotation: currVal = 225 + 55 – (10 * 7) = 210
.
.
.
Last rotation: currVal = 285 + 55 – (10 * 1) = 330

Previous currVal was 285, now it becomes 330.
It’s the maximum value we can find hence return 330.

Follow the steps mentioned below to implement the above approach:

  • Compute the sum of all array elements. Let this sum be ‘arrSum‘.
  • Compute R0 for the given array. Let this value be currVal.
  • Loop from j = 1 to N-1 to calculate the value for each rotation:
    • Update the currVal using the formula mentioned above.
    • Update the maximum sum accordingly in each step.
  • Return the maximum value as the required answer.

Below is the implementation of the above idea.

C++




// C++ program to find max value of i*arr[i]
#include <iostream>
using namespace std;
 
// Returns max possible value of i*arr[i]
int maxSum(int arr[], int n)
{
    // Find array sum and i*arr[i] with no rotation
    int arrSum = 0; // Stores sum of arr[i]
    int currVal = 0; // Stores sum of i*arr[i]
    for (int i = 0; i < n; i++) {
        arrSum = arrSum + arr[i];
        currVal = currVal + (i * arr[i]);
    }
 
    // Initialize result as 0 rotation sum
    int maxVal = currVal;
 
    // Try all rotations one by one and find
    // the maximum rotation sum.
    for (int j = 1; j < n; j++) {
        currVal = currVal + arrSum - n * arr[n - j];
        if (currVal > maxVal)
            maxVal = currVal;
    }
 
    // Return result
    return maxVal;
}
 
// Driver program
int main(void)
{
    int arr[] = { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << "\nMax sum is " << maxSum(arr, n);
    return 0;
}


Java




// Java program to find max value of i*arr[i]
 
import java.util.Arrays;
 
class Test {
    static int arr[]
        = new int[] { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
    // Returns max possible value of i*arr[i]
    static int maxSum()
    {
        // Find array sum and i*arr[i] with no rotation
        int arrSum = 0; // Stores sum of arr[i]
        int currVal = 0; // Stores sum of i*arr[i]
        for (int i = 0; i < arr.length; i++) {
            arrSum = arrSum + arr[i];
            currVal = currVal + (i * arr[i]);
        }
 
        // Initialize result as 0 rotation sum
        int maxVal = currVal;
 
        // Try all rotations one by one and find
        // the maximum rotation sum.
        for (int j = 1; j < arr.length; j++) {
            currVal = currVal + arrSum
                      - arr.length * arr[arr.length - j];
            if (currVal > maxVal)
                maxVal = currVal;
        }
 
        // Return result
        return maxVal;
    }
 
    // Driver method to test the above function
    public static void main(String[] args)
    {
        System.out.println("Max sum is " + maxSum());
    }
}


Python




'''Python program to find maximum value of Sum(i*arr[i])'''
 
# returns max possible value of Sum(i*arr[i])
 
 
def maxSum(arr):
 
    # stores sum of arr[i]
    arrSum = 0
 
    # stores sum of i*arr[i]
    currVal = 0
 
    n = len(arr)
 
    for i in range(0, n):
        arrSum = arrSum + arr[i]
        currVal = currVal + (i*arr[i])
 
    # initialize result
    maxVal = currVal
 
    # try all rotations one by one and find the maximum
    # rotation sum
    for j in range(1, n):
        currVal = currVal + arrSum-n*arr[n-j]
        if currVal > maxVal:
            maxVal = currVal
 
    # return result
    return maxVal
 
 
# test maxsum(arr) function
if __name__ == '__main__':
    arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    print "Max sum is: ", maxSum(arr)


C#




// C# program to find max value of i*arr[i]
using System;
 
class Test {
    static int[] arr
        = new int[] { 10, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
    // Returns max possible value of i*arr[i]
    static int maxSum()
    {
        // Find array sum and i*arr[i]
        // with no rotation
        int arrSum = 0; // Stores sum of arr[i]
        int currVal = 0; // Stores sum of i*arr[i]
 
        for (int i = 0; i < arr.Length; i++) {
            arrSum = arrSum + arr[i];
            currVal = currVal + (i * arr[i]);
        }
 
        // Initialize result as 0 rotation sum
        int maxVal = currVal;
 
        // Try all rotations one by one and find
        // the maximum rotation sum.
        for (int j = 1; j < arr.Length; j++) {
            currVal = currVal + arrSum
                      - arr.Length * arr[arr.Length - j];
            if (currVal > maxVal)
                maxVal = currVal;
        }
 
        // Return result
        return maxVal;
    }
 
    // Driver Code
    public static void Main()
    {
        Console.WriteLine("Max sum is " + maxSum());
    }
}
 
// This article is contributed by vt_m.


Javascript




<script>
// JavaScript program to find max value of i*arr[i]
 
// Returns max possible value of i*arr[i]
function maxSum(arr, n)
{
    // Find array sum and i*arr[i] with no rotation
    let arrSum = 0; // Stores sum of arr[i]
    let currVal = 0; // Stores sum of i*arr[i]
    for (let i=0; i<n; i++)
    {
        arrSum = arrSum + arr[i];
        currVal = currVal+(i*arr[i]);
    }
 
    // Initialize result as 0 rotation sum
    let maxVal = currVal;
 
    // Try all rotations one by one and find
    // the maximum rotation sum.
    for (let j=1; j<n; j++)
    {
        currVal = currVal + arrSum-n*arr[n-j];
        if (currVal > maxVal)
            maxVal = currVal;
    }
 
    // Return result
    return maxVal;
}
 
// Driver program
    let arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    let n = arr.length;
    document.write("Max sum is " + maxSum(arr, n));
 
 
 
 
 
 
// This code is contributed by Surbhi Tyagi.
</script>


PHP




<?php
// PHP program to find max
// value of i*arr[i]
 
// Returns max possible
// value of i*arr[i]
function maxSum($arr, $n)
{
    // Find array sum and
    // i*arr[i] with no rotation
     
    // Stores sum of arr[i]
    $arrSum = 0;
     
    // Stores sum of i*arr[i]
    $currVal = 0;
    for ($i = 0; $i < $n; $i++)
    {
        $arrSum = $arrSum + $arr[$i];
        $currVal = $currVal +
                  ($i * $arr[$i]);
    }
 
    // Initialize result as
    // 0 rotation sum
    $maxVal = $currVal;
 
    // Try all rotations one
    // by one and find the
    // maximum rotation sum.
    for ($j = 1; $j < $n; $j++)
    {
        $currVal = $currVal + $arrSum -
                   $n * $arr[$n - $j];
        if ($currVal > $maxVal)
            $maxVal = $currVal;
    }
 
    // Return result
    return $maxVal;
}
 
// Driver Code
$arr = array (10, 1, 2, 3, 4,
              5, 6, 7, 8, 9);
$n = sizeof($arr);
echo "Max sum is " ,
     maxSum($arr, $n);
 
// This code is contributed by m_kit
?>


Output

Max sum is 330









Time Complexity: O(N) 
Auxiliary Space: O(1)



Previous Article
Next Article

Similar Reads

Maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]| when elements are from 1 to n
Given an array arr[] of size n whose elements are from the range [1, n]. The task is to find maximum value of |arr[0] - arr[1]| + |arr[1] - arr[2]| + ... +|arr[n - 2] - arr[n - 1]|. You can arrange the numbers in the array in any order. Examples: Input: arr[] = {1, 2, 3, 4} Output: 7 Arrange the array in this way for max value, arr[] = {3, 1, 4, 2}
3 min read
Count pairs (i, j) from an array such that |arr[i]| and |arr[j]| both lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|
Given an array arr[] of size N, the task is to count the number of pairs (arr[i], arr[j]) such that |arr[i]| and |arr[j]| lies between |arr[i] - arr[j]| and |arr[i] + arr[j]|. Examples: Input: arr[] = {1, 3, 5, 7} Output: 2 Explanation: Pair (arr[1], arr[2]) (= (3, 5)) lies between |3 - 5| (= 2) and |3 + 5| (= 8).Pair (arr[2], arr[3]) (= (5, 7)) li
6 min read
Check whether (i,j) exists such that arr[i] != arr[j] and arr[arr[i]] is equal to arr[arr[j]]
Given an array A[]. The task is to determine if it is possible to choose two indices 'i' and 'j' such that the below conditions gets satisfied:- A[i] is not equal to A[j].A[A[i]] is equal to A[A[j]]. Note: The value of the elements in an array is less than the value of N i.e. For every i, arr[i] &lt; N. Examples: Input: N = 4, A[] = {1, 1, 2, 3} Ou
10 min read
Minimize last remaining element of Array by selecting pairs such that arr[i] &gt;= arr[j] and replace arr[i] with arr[i] - arr[j]
Given an array arr[] of N positive integers, the task is to find the smallest possible value of the last remaining element in the array after performing the following operations any number of times: Select a pair of indices (i, j) such that arr[i] &gt;= arr[j] and replace arr[i] with arr[i] - arr[j].If an array element arr[i] &lt;= 0, remove it fro
5 min read
Maximum value of (arr[i] * arr[j]) + (arr[j] - arr[i])) possible for any pair in an array
Given an array arr[] consisting of N integers, the task is to find the maximum possible value of the expression (arr[i] * arr[j]) + (arr[j] - arr[i])) for any pair (i, j), such that i ? j and 0 ? (i, j) &lt; N. Examples: Input: arr[] = {-2, -8, 0, 1, 2, 3, 4}Output: 22Explanation:For the pair (-8, -2) the value of the expression (arr[i] * arr[j]) +
6 min read
Count pairs in an array such that LCM(arr[i], arr[j]) &gt; min(arr[i],arr[j])
Given an array arr[], the task is to find the count of pairs in the array such that LCM(arr[i], arr[j]) &gt; min(arr[i], arr[j]) Note: Pairs (arr[i], arr[j]) and (arr[j], arr[i]) are considered identical and will be counted only once. Examples: Input: arr[] = {1, 1, 4, 9} Output: 5 All valid pairs are (1, 4), (1, 9), (1, 4), (1, 9) and (4, 9). Inpu
9 min read
Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
11 min read
Count quadruples (i, j, k, l) in an array such that i &lt; j &lt; k &lt; l and arr[i] = arr[k] and arr[j] = arr[l]
Given an array arr[] consisting of N integers, the task is to count the number of tuples (i, j, k, l) from the given array such that i &lt; j &lt; k &lt; l and arr[i] = arr[k] and arr[j] = arr[l]. Examples: Input: arr[] = {1, 2, 1, 2, 2, 2} Output: 4 Explanation: The tuples which satisfy the given condition are: 1) (0, 1, 2, 3) since arr[0] = arr[2
6 min read
Python3 Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Javascript Program to Rearrange array such that arr[i] &gt;= arr[j] if i is even and arr[i]&lt;=arr[j] if i is odd and j &lt; i
Given an array of n elements. Our task is to write a program to rearrange the array such that elements at even positions are greater than all elements before it and elements at odd positions are less than all elements before it.Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 7} Output : 4 5 3 6 2 7 1 Input : arr[] = {1, 2, 1, 4, 5, 6, 8, 8} Output : 4
3 min read
Find Maximum value of abs(i - j) * min(arr[i], arr[j]) in an array arr[]
Given an array of n distinct elements. Find the maximum of product of Minimum of two numbers in the array and absolute difference of their positions, i.e., find maximum value of abs(i - j) * min(arr[i], arr[j]) where i and j vary from 0 to n-1. Examples : Input : arr[] = {3, 2, 1, 4} Output: 9 // arr[0] = 3 and arr[3] = 4 minimum of them is 3 and /
7 min read
Count number of pairs (i, j) such that arr[i] * arr[j] &gt; arr[i] + arr[j]
Given an array arr[] of non-negative integers, the task is to count pairs of indices (i, j such that arr[i] * arr[j] &gt; arr[i] + arr[j] where i &lt; j. Examples: Input: arr[] = { 5, 0, 3, 1, 2 } Output: 3 Input: arr[] = { 1, 1, 1 } Output: 0 Naive Approach: Run two nested loops and check for every pair whether the condition is satisfied. If the c
9 min read
Count the number of pairs (i, j) such that either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]
Given an array arr[] of N integers, the task is to find the count of unordered index pairs (i, j) such that i != j and 0 &lt;=i &lt; j &lt; N and either arr[i] is divisible by arr[j] or arr[j] is divisible by arr[i]. Examples: Input: arr[] = {2, 4} Output: 1 (0, 1) is the only index pair possible. Input: arr[] = {3, 2, 4, 2, 6} Output: 6 Possible p
7 min read
Count number of pairs (i, j) such that arr[i] * arr[j] = arr[i] + arr[j]
Given an array arr[] of length N, count the number of pairs (i, j) such that arr[i] * arr[j] = arr[i] + arr[j] and 0 &lt;= i &lt; j &lt;= N. It is also given that elements of the array can be any positive integers including zero. Examples: Input : arr[] = {2, 0, 3, 2, 0} Output : 2 Input : arr[] = {1, 2, 3, 4} Output : 0 Simple solution: We can gen
8 min read
Count of pairs (arr[i], arr[j]) such that arr[i] + j and arr[j] + i are equal
Given an array arr[], the task is to count pairs i, j such that, i &lt; j and arr[i] + j = arr[j] + i. Examples: Input: arr[] = {4, 1, 2, 3}Output: 3Explanation: In total three pairs are satisfying the given condition those are {1, 2}, {2, 3} and {1, 3}.So, the final answer is 3. Input: arr[] = {1, 5, 6}Output: 1 Naive Approach: The naive approach
5 min read
Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i &lt; j &lt; k &lt; l
Maximize arr[j] - arr[i] + arr[l] - arr[k], such that i &lt; j &lt; k &lt; l. Find the maximum value of arr[j] - arr[i] + arr[l] - arr[k], such that i &lt; j &lt; k &lt; l Example: Let us say our array is {4, 8, 9, 2, 20} Then the maximum such value is 23 (9 - 4 + 20 - 2)Recommended PracticeMaximum valueTry It! Brute Force Method: We can simply fin
11 min read
Given an array arr[], find the maximum j - i such that arr[i] <= arr[j]
Given an array arr[] of N positive integers. The task is to find the maximum of j - i subjected to the constraint of arr[i] &lt;= arr[j]. Examples : Input: {34, 8, 10, 3, 2, 80, 30, 33, 1} Output: 6 (j = 7, i = 1) Input: {9, 2, 3, 4, 5, 6, 7, 8, 18, 0} Output: 8 ( j = 8, i = 0) Input: {1, 2, 3, 4, 5, 6} Output: 5 (j = 5, i = 0) Input: {6, 5, 4, 3,
15+ min read
Maximum value of expression (arr[i] + arr[j] * arr[k]) formed from a valid Triplet
Given an array arr[] of N integers. The task is to find the maximum value of (arr[i] + arr[j] * arr[k]) among every triplet (i, j, k) such that arr[i] &lt; arr[j] &lt; arr[k] and i &lt; j &lt; k. If there doesn't exist any such triplets then print “-1". Examples: Input: arr[]={7, 9, 3, 8, 11, 10}Output: 106Explanation:The valid triplets are:1) (7,
14 min read
Find a triplet (i, j, k) from an array such that i &lt; j &lt; k and arr[i] &lt; arr[j] &gt; arr[k]
Given an array arr[] which consists of a permutation of first N natural numbers, the task is to find any triplet (i, j, k) from the given array such that 0 ? i &lt; j &lt; k ? (N - 1) and arr[i] &lt; arr[j] and arr[j] &gt; arr[k]. If no such triplet exists, then print "-1". Examples: Input: arr[] = {4, 3, 5, 2, 1, 6}Output: 1 2 3Explanation: For th
5 min read
Find triplet (i, j, k) to maximize (P * arr[i] + Q * arr[j] + R * arr[k])
Given an array arr[] of size N and three numbers P, Q, and R. The task is to find three indices named (i, j, k) in the given array such that i &lt; j &lt; k, and the value of equation (P * arr[i] + Q * arr[j] + R * arr[k]) should be maximum. Examples: Input: arr[] = {1, 2, 3, 4, 5}, P = 1, Q = 2, R = 3Output: 2 3 4Explanation: For the given array t
15+ min read
Python Program to Find the Maximum sum of i*arr[i] among all rotations of a given array
Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2} Output: 29 Explanation: Lets look at all the rotations, {8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11 {3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29 {1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27
6 min read
Rearrange array to maximize count of triplets (i, j, k) such that arr[i] &gt; arr[j] &lt; arr[k] and i &lt; j &lt; k
Given an array, arr[] of size N, the task is to rearrange the array elements to maximize the count of triplets (i, j, k) that satisfy the condition arr[i] &gt; arr[j] &lt; arr[k] and i &lt; j &lt; k. Examples: Input: arr[] = {1, 4, 3, 3, 2, 2, 5} Output: Count of triplets: 3 Array: {3, 1, 3, 2, 4, 2, 5} Explanation:Rearrange the array to {3, 1, 3,
8 min read
Check if an array arr[] can be rearranged such that arr[2 × i + 1] = 2* arr[2 × i] for every ith index
Given an array arr[] consisting of 2*N integers, the task is to check if it is possible to rearrange the array elements such that arr[2 * i + 1] = 2* arr[2 * i] for every ith index. If it is possible to do so, then print "Yes. Otherwise, print "No". Examples: Input: arr[] = {4, -2, 2, -4}, N = 2Output: YesExplanation: Rearrange the array as arr[] =
8 min read
Count of jumps to reach the end of Array by jumping from arr[i] to arr[arr[i]]
Given an array arr[] of N integers, the task is to find the number of jumps required to escape the array arr[] for all values of i as the starting indices in the range [0, N) where the only possible jump from arr[i] is to arr[arr[i]] and escaping the array means arr[i]&gt;=N, i.e, the index for the next jump does not exist. Examples: Input: arr[] =
10 min read
Sort Array by choosing indices i, j, k and replacing arr[i] with arr[j] - arr[k]
Given an array arr[] of N integers, the task is to sort the array by replacing any element at index i (arr[i]) with arr[j] - arr[k] such that i &lt; j &lt; k. Note: If no operation is needed print 0. Examples: Input: arr[] = {2, -2, -3, -1, 3}Output:33 4 52 4 51 4 5Explanation: The number at 3rd position can be replaced by 4th and last position. Th
9 min read
Rearrange an array so that arr[i] becomes arr[arr[i]] with O(1) extra space
Given an array arr[] of size n where every element is in the range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. This should be done with O(1) extra space Examples: Input: arr[] = {3, 2, 0, 1}Output: arr[] = {1, 0, 3, 2}Explanation: In the given array arr[arr[0]] is 1 so arr[0] in output array is 1arr[arr[1]] is 0 so
7 min read
Convert Array into Zig-Zag fashion (arr[i-1] < arr[i] > arr[i+1])
Given an array of distinct elements of size N, the task is to rearrange the elements of the array in a zig-zag fashion, i.e., the elements are arranged as smaller, then larger, then smaller, and so on. There can be more than one arrangement that follows the form: arr[0] &lt; arr[1] &gt; arr[2] &lt; arr[3] &gt; arr[4] &lt; ... Examples: Input: N = 7
12 min read
Maximum value of arr[i] % arr[j] for a given array
Given an array arr[], the task is to find the maximum value of arr[i] % arr[j] for all possible pairs.Examples: Input: arr[] = { 2, 3 } Output: 2 2 % 3 = 2 3 % 2 = 1 Input: arr[] = { 2, 2, 2, 2 } Output: 0 Naive Approach: Run two nested loops and calculate the value of arr[i] % arr[j] for every pair. Update the answer according to the value calcula
13 min read
Longest chain of arr[i], arr[arr[i]], .. without repetition
Given an array of size n such that elements in array are distinct and in range from 0 to n-1. We need to find out length of the longest chain {arr[i], arr[arr[i]], arr[arr[arr[i]]]......} such that no set element repeats. Examples: Input : arr[] = [5, 4, 0, 3, 1, 6, 2] Output :4 Explanation: The longest chain without repetition is {arr[0], arr[5],
7 min read
Check whether there exists a triplet (i, j, k) such that arr[i] &lt; arr[k] &lt; arr[j] for i &lt; j &lt; k
Given an array arr[], the task is to check that if there exist a triplet (i, j, k) such that arr[i]&lt;arr[k]&lt;arr[j] and i&lt;j&lt;k then print Yes else print No. Examples: Input: arr[] = {1, 2, 3, 4, 5}Output: NoExplanation:There is no such sub-sequence such that arr[i] &lt; arr[k] &lt; arr[j] Input: arr[] = {3, 1, 5, 0, 4}Output: YesExplanatio
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg