Open In App

Maximizing Circular Array Iterations

Last Updated : 12 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a circularly connected array A[] of length N, you are allowed to rearrange the numbers in the array initially in any order to maximize the number of iterations, the task is to determine the maximum number of iterations that can be made by choosing a starting index i (1 <= i <= N) optimally and following the simulation rules below:

  • If the current element A[i] is greater than 0, decrement the current element by 1.
  • Move to the adjacent right element (circularly connected).

Examples:

Input: N = 3, A[] = {2, 1, 1}
Output: 4
Explanation: One of the optimal orders in which numbers can be arranged: 1->2->3->1 with 4 iterations maximum.

Input: N = 4, A[] = {3, 0, 2, 1}
Output: 3
Explanation: One of the orders in which all the numbers can be arranged is: 4->3->1->2 i.e. A[] = { 1, 2, 3, 0 } with 3 iterations maximum.

Approach: To solve the problem follow the below observations:

Observations:

  • It is best to start with the highest number and end with the lowest. So sort the array in descending order.
  • The minimum number will provide a bottleneck to the array as we stop whenever any number becomes 0.
  • For each iteration, each number decrements by 1. We can iterate fully till minimum > 0 and the answer increases by N.
  • When the minimum becomes 0, we would like to iterate all the numbers greater than 0 in the last. As soon as the number becomes 0, we stop.
  • If minimum is last number , then we can perform total of minimum*N iterations . After that, we know that only those greater than minimum can iterate . So find position of that last number .

Steps to solve the problem:

  • Sort the array in descending order.
  • Let answer be ans.
  • If the last element is minimum , add (minimum*N) to ans
  • Iterate through the array and if A[i] == minimum, add i to ans.

Below is the implementation of the above approach:

C++




// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the
// maximum number of iterations
int helper(int A[], int N)
{
 
    sort(A, A + N, greater<int>());
 
    int minimum = A[N - 1];
    int pos;
    for (int i = 0; i < N; i++) {
        if (A[i] == minimum) {
 
            // The first position which
            // is minimum
            pos = i;
            break;
        }
    }
    return (minimum * N + pos);
}
 
// Driver Code
int main()
{
    int N = 4;
    int A[] = { 3, 0, 2, 1 };
 
    // Function Call
    cout << helper(A, N);
    return 0;
}


Java




import java.util.*;
 
public class MaxIterations {
 
    // Function to find the maximum number of iterations
    static int helper(int[] A, int N)
    {
        Arrays.sort(A);
        for (int i = 0, j = N - 1; i < j; i++, j--) {
            int temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
 
        int minimum = A[N - 1];
        int pos = 0;
        for (int i = 0; i < N; i++) {
            if (A[i] == minimum) {
                // The first position which is minimum
                pos = i;
                break;
            }
        }
        return (minimum * N + pos);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 4;
        int[] A = { 3, 0, 2, 1 };
 
        // Function Call
        System.out.println(helper(A, N));
    }
}


Python3




# Function to find the maximum number of iterations
def helper(A):
    # Sort the array in descending order
    A.sort(reverse=True)
 
    # Find the minimum element and its position
    minimum = A[-1]
    pos = 0
    for i in range(len(A)):
        if A[i] == minimum:
            # The first position which is minimum
            pos = i
            break
 
    return minimum * len(A) + pos
 
# Driver Code
if __name__ == "__main__":
    N = 4
    A = [3, 0, 2, 1]
 
    # Function Call
    print(helper(A))


C#




// C# program to implement
// the above approach
using System;
using System.Linq;
 
class Program
{
    // Function to find the
    // maximum number of iterations
    static int Helper(int[] A, int N)
    {
        Array.Sort(A);
        Array.Reverse(A);
 
        int minimum = A[N - 1];
        int pos = 0;
        for (int i = 0; i < N; i++)
        {
            if (A[i] == minimum)
            {
 
                // The first position which
                // is minimum
                pos = i;
                break;
            }
        }
        return (minimum * N + pos);
    }
 
    // Driver Code
    static void Main(string[] args)
    {
        int N = 4;
        int[] A = { 3, 0, 2, 1 };
 
        // Function Call
        Console.WriteLine(Helper(A, N));
    }
}


Javascript




// Function to find the maximum number of iterations
function helper(A) {
    // Sort the array in descending order
    A.sort((a, b) => b - a);
 
    // Find the minimum element and its position
    let minimum = A[A.length - 1];
    let pos = 0;
    for (let i = 0; i < A.length; i++) {
        if (A[i] === minimum) {
            // The first position which is minimum
            pos = i;
            break;
        }
    }
 
    return minimum * A.length + pos;
}
 
// Driver Code
const N = 4;
const A = [3, 0, 2, 1];
 
// Function Call
console.log(helper(A));


Output

3








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



Similar Reads

Count of iterations to make minimum as 0 by rotating Array followed by reducing it from original Array
Given an array arr[]. The task is to find the number of iterations required to make the minimum element in the array as 0. In one iteration, left rotate the array by one and subtract the corresponding element of the original array and rotated array. Examples: Input: arr[] = { 2, 6, 3, 4, 8, 7 }Output: 3Explanation: Refer to the image below for expl
11 min read
Fill array with 1's using minimum iterations of filling neighbors
Given an array of 0s and 1s, in how many iterations the whole array can be filled with 1s if in a single iteration immediate neighbors of 1s can be filled. Note: if we cannot fill array with 1s, then print "-1" . Examples : Input : arr[] = {1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1}Output : 1Explanation: To convert the whole array into 1s, one it
9 min read
Minimum no. of iterations to pass information to all nodes in the tree
Given a very large n-ary tree. Where the root node has some information which it wants to pass to all of its children down to the leaves with the constraint that it can only pass the information to one of its children at a time (take it as one iteration). Now in the next iteration the child node can transfer that information to only one of its chil
21 min read
Number of chocolates left after k iterations
Given a pile of chocolates and an integer 'k' i.e. the number of iterations, the task is to find the number of chocolates left after k iterations. Note: In every iteration, we can choose a pile with a maximum number of chocolates, after that square root of chocolate remains and rest is eaten. Examples: Input: Chocolates = 100000000, Iterations = 3
4 min read
Find probability of selecting element from kth column after N iterations
Given a matrix M of order N*M where Mij represent the occurrence of j in row i. The task is to find the probability of occurrence of given k in last row after applying the given operation: Starting from 1st row, we select one element from any column of the entire row, and add it to the same column of next row. We repeating this till the last row. E
7 min read
Find the sum of remaining sticks after each iterations
Given N number of sticks of varying lengths in an array arr, the task is to determine the sum of the count of sticks that are left after each iteration. At each iteration, cut the length of the shortest stick from remaining sticks. Examples: Input: N = 6, arr = {5, 4, 4, 2, 2, 8} Output: 7 Explanation: Iteration 1: Initial arr = {5, 4, 4, 2, 2, 8}
8 min read
Minimize total cost without repeating same task in two consecutive iterations
Given an array arr[][] of size M X N where M represents the number of tasks and N represents number of iteration. An entry in the array arr[i][j] represents the cost to perform task j at the ith iteration. Given that the same task j cannot be computed in two consecutive iterations, the task is to compute the minimum cost to perform exactly one task
14 min read
Find Binary string by converting all 01 or 10 to 11 after M iterations
Given a binary string str[] of size N and an integer M. This binary string can be modified by flipping all the 0's to 1 which have exactly one 1 as a neighbour. The task is to find the final state of the binary string after M such iterations.Note: 2?N?103, 1?M?109 Examples: Input: str="01100", M=1Output: 11110Explanation: After First Iteration: 111
8 min read
JavaScript Program to Find i’th Index Character in a Binary String Obtained After n Iterations
Given a decimal number m, convert it into a binary string and apply n iterations. In each iteration, 0 becomes “01” and 1 becomes “10”. Find the (based on indexing) index character in the string after the nth iteration. Input: m = 5, n = 2, i = 3Output: 1Input: m = 3, n = 3, i = 6Output: 1Approach 1Convert a decimal number into its binary represent
3 min read
Find i’th index character in a binary string obtained after n iterations | Set 2
Given a decimal number m, convert it into a binary string and apply n iterations, in each iteration 0 becomes “01” and 1 becomes “10”. Find ith(based indexing) index character in the string after nth iteration.Examples: Input: m = 5 i = 5 n = 3Output: 1ExplanationIn the first case m = 5, i = 5, n = 3. Initially, the string is 101 ( binary equivalen
13 min read