in ,

Maximize Bitwise OR of Array by incrementing elements by at most K

import java.io.*;

  

class Main {

  

    static void MaximizeBitwiseOR(long[] a, int k, int n)

    {

  

        

        

        long or = 0;

        long bitwiseOr = 0;

        for (int i = 0; i < a.length; ++i) {

            bitwiseOr |= a[i];

        }

  

        for (int i = 60; i >= 0; i--) {

            if (((1L << i) & bitwiseOr) == 0) {

  

                long minSteps = Long.MAX_VALUE;

                int mini = -1;

                for (int j = 0; j < n; j++) {

  

                    long y = ((1L << i) - 1) & a[j];

                    long steps = (1L << i) - y;

  

                    if (steps <= k

                        && steps < minSteps) {

                        minSteps = steps;

                        mini = j;

                    }

                }

                if (mini != -1) {

  

                    k -= minSteps;

                    a[mini] += minSteps;

                    long orr = 0;

                    for (int j = 0; j < n; j++) {

                        orr |= a[j];

                    }

                    bitwiseOr = orr;

                }

            }

        }

  

        

        for (long elements : a) {

            System.out.print(elements + " ");

        }

    }

  

    

    public static void main(String[] args)

    {

        int N = 6;

        int K = 2;

        long arr[] = { 1, 3, 7, 0, 6, 1 };

  

        MaximizeBitwiseOR(arr, K, N);

    }

}

What do you think?

Silver 1

Written by yulica

Leave a Reply

Your email address will not be published.

      Android vs iOS Development: Pros and Cons of Each Platform_61d8c364a6197.jpeg

      Android vs iOS Development: Pros and Cons of Each Platform

      Mobile App Development Trends for 2020_61d8c2bb8874c.jpeg

      Mobile App Development Trends for 2020