Wednesday, June 8, 2022
HomeWordPress DevelopmentDecrease steps to create given Array by including powers of two

Decrease steps to create given Array by including powers of two


Given an array A[] having N optimistic integers, the duty is to seek out the minimal variety of steps to construct this array from an preliminary array of measurement N having all 0s following the under operations:

  • Choose any subsequence of the array.
  • Add any energy of 2 to every aspect of the subsequence.

Examples:

Enter: A = {5, 5, 5}, N = 3
Output: 2
Clarification: Initially, A = {0, 0, 0}
First, add 4 (22) to all components of A.
A turns into {4, 4, 4}.
Then, add 1  (20) to all components of A.
A now turns into {5, 5, 5}
Due to this fact, two operations have been required to equalize A2 and A1.

Enter: A1 = [5, 2, 1], N  = 3
Output: 3

 

Strategy: The answer to the issue relies on the next mathematical idea:

Every quantity will be expressed because the sum of exponents of two, i.e., the binary illustration.
To get a quantity in minimal steps by including powers of two to 0, we have to add solely the powers of set bits.
To attenuate the step for forming the array, the optimum alternative is to pick out all the weather having set bit in the identical place directly and carry out the operation in all of them.

Due to this fact, the issue reduces to discovering the overall variety of distinctive set bit positions in all of the array components.

Comply with the steps talked about under to implement the concept:

  • As we want the distinctive set bits amongst all of the array components, we should always carry out the bitwise OR of all the weather and rely the set bits of that worth.
  • Initialize a variable (say X) to retailer the bitwise OR of all of the array components.
  • Iterate via all of the array components:
    • Carry out the bitwise OR operation with X.
  • Calculate the set bits in X.
  • The rely of set bits is the required reply.

Under is the implementation of the above strategy.

Python3

  

def minimumOperations(A, n):

      

    

    

    bitwiseOr = A[0]

      

    

    

    for i in vary(1, n):

        bitwiseOr |= A[i]

          

    

    

    ans = bin(bitwiseOr).rely("1")

      

    

    

    return ans

  

if __name__ == '__main__':

    A = [5, 2, 1]

    N = 3

      

    

    print(minimumOperations(A, N))

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

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments