GFG App
Open App
Browser
Continue

# Minimize the Array sum by inverting 0 bit K times

Given an array arr[] of size N and an integer K, the task is to invert the 0 bit (unset bit) of any integer of given array total K times, such that the overall sum of arr gets minimized.

Examples:

Input: arr = {3, 7, 3}, K = 2
Output: 21
Explanation: Binary representation 3 is 11, and 7 is 111.
Since we need to set 2 bits, we can set the lowest unset bits
of the two 3s such that they become 111.
The total sum is then 7 + 7 + 7 = 21.

Input: arr = {2, 3, 4}, K = 2
Output: 11

### Approach: Greedy algorithm:

The idea of solving this problem can be done by using the greedy technique. We will change the rightmost 0s to 1s.

Follow the steps below to implement the above idea:

• Iterate over the elements of the array.
• Convert the element into its binary representation and iterate over the bits of binary representation.
• Check for its ith bit is unset or not.
• If the ith bit is unset then, Push the ith position into the array smallestUnsetBit.
• Sort the smallestUnsetBit array.
• Iterate over the smallestUnsetBit for K time and calculate the value for smallestUnsetBit[i] by 2smallestUnsetBit[i], this value will contribute into the overall sum after inverting smallestUnsetBit[i] bit.
• Return the result.

Below is the implementation of the above approach:

## C++

```// C++ code to implement the approach:

#include <bits/stdc++.h>
using namespace std;
#define mod (1e9 + 7)

// Function to find the minimum sum
int minSum(vector<int>& nums, int k)
{
vector<int> smallestUnsetBit;

// Iterate over the elements of
// given array
for (auto num : nums) {

// Converting the number to its
// binary representation
string s = bitset<31>(num).to_string();
for (int i = 30; i >= 0; i--) {

// Check if the ith bit is
// unset or not
if (s[i] == '0') {

// Push ith unset bit
// into smallestUnsetBit
smallestUnsetBit.push_back(30 - i);
}
}
}

// Sort the unsetbits in
// ascending order.
sort(smallestUnsetBit.begin(),
smallestUnsetBit.end());

// Calculate the overall sum
// of given array
long long result
= accumulate(nums.begin(), nums.end(), 0LL);

int i = 0;

// Add the overall effect of sum in
// the result by inverting the '0' bits.
while (k--) {
result
= (result
+ (long long)pow(2, smallestUnsetBit[i++]))
% (long long)mod;
}

// Return the result
return result % (long long)mod;
}

// Driver function
int main()
{
vector<int> arr = { 3, 7, 3 };
int K = 2;

// Function call
int result = minSum(arr, K);
cout << result << endl;
return 0;
}```

## Java

```/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG {

static int minSum(ArrayList<Integer> nums, int k){

ArrayList<Integer> smallestUnsetBit = new ArrayList<>();

// Iterate over the elements of
// given array
for (int num : nums) {

// Converting the number to its
// binary representation
String s = Integer.toBinaryString(num);
int len = s.length();
for(int i=0;i<31-len;i++){
s = "0" + s;
}

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

// Check if the ith bit is
// unset or not
if (s.charAt(i) == '0') {

// Push ith unset bit
// into smallestUnsetBit
}
}
}

Collections.sort(smallestUnsetBit);

// Calculate the overall sum
// of given array
long result = 0;

for(int i:nums){
result+=i;
}

int i = 0;

// Add the overall effect of sum in
// the result by inverting the '0' bits.
while (k-->0) {
result = (result + (long)Math.pow(2, smallestUnsetBit.get(i++)))  % (long)(1e+7);
}

// Return the result
return (int)(result % (long)(1e+7));

}

public static void main (String[] args) {

ArrayList<Integer> arr = new ArrayList<>();
int K = 2;
// Function call
int result = minSum(arr, K);
System.out.println(result);
}
}

// This code is contributed by aadityaburujwale.```

## Python3

```# Python code for the above approach
import math
mod = 1e9 + 7

# Function to find the minimum sum
def minSum(nums, k):

smallestUnsetBit =[];

# Iterate over the elements of
# given array
for num in nums:

# Converting the number to its
# binary representation
s = "{0:032b}".format(num);
for i in range(30,1,-1):

# Check if the ith bit is
# unset or not
if (s[i] == '0'):

# Push ith unset bit
# into smallestUnsetBit
smallestUnsetBit.append(30 - i);

# Sort the unsetbits in
# ascending order.
smallestUnsetBit.sort()

# Calculate the overall sum
# of given array
result = 0;
for num in nums:
result = result + num;

i = 0;

# Add the overall effect of sum in
# the result by inverting the '0' bits.
while k >= 0:
result = (result+ math.pow(2, smallestUnsetBit[i])) % mod;
k = k - 1;
i = i + 1;

# Return the result
return result % mod;

# Driver function
arr = [3, 7, 3 ];
K = 2;

# Function call
result = int(minSum(arr, K));
print(result);

# This code is contributed by Potta Lokesh
```

## C#

```// C# code to implement the approach:
using System;
using System.Collections.Generic;

public class GFG {

static int minSum(List<int> nums, int k)
{

List<int> smallestUnsetBit = new List<int>();

// Iterate over the elements of
// given array
foreach(int num in nums)
{

// Converting the number to its
// binary representation
String s = Convert.ToString(num, 2);
int len = s.Length;
for (int i = 0; i < 31 - len; i++) {
s = "0" + s;
}

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

// Check if the ith bit is
// unset or not
if (s[i] == '0') {

// Push ith unset bit
// into smallestUnsetBit
}
}
}

smallestUnsetBit.Sort();

// Calculate the overall sum
// of given array
long result = 0;

foreach(int i in nums) { result += i; }

int j = 0;

// Add the overall effect of sum in
// the result by inverting the '0' bits.
while (k-- > 0) {
result = (result
+ (long)Math.Pow(
2, smallestUnsetBit[j++]))
% (long)(1e+7);
}

// Return the result
return (int)(result % (long)(1e+7));
}

static public void Main()
{

List<int> arr = new List<int>();
int K = 2;
// Function call
int result = minSum(arr, K);
Console.WriteLine(result);
}
}

// This code is contributed by Rohit Pradhan```

## Javascript

```    <script>
// JavaScript code to implement the approach:

const mod = 1e9 + 7;

// Function to find the minimum sum
const minSum = (nums, k) => {
let smallestUnsetBit = [];

// Iterate over the elements of
// given array
for (let indx in nums) {

// Converting the number to its
// binary representation

let s_next = (nums[indx] >>> 0).toString(2);
let s = "";
for (let i = 0; i < 31 - s_next.length; ++i) s += "0";

s += s_next;

for (let i = 30; i >= 0; i--) {

// Check if the ith bit is
// unset or not
if (s[i] == '0') {

// Push ith unset bit
// into smallestUnsetBit
smallestUnsetBit.push(30 - i);
}
}
}

// Sort the unsetbits in
// ascending order.
smallestUnsetBit.sort((a, b) => a - b);

// Calculate the overall sum
// of given array
let result = 0;

for (let indx in nums) result += nums[indx];

let i = 0;

// Add the overall effect of sum in
// the result by inverting the '0' bits.
while (k--) {
result = (result + Math.pow(2, smallestUnsetBit[i++])) % mod;
}

// Return the result
return result % mod;
}

// Driver function

let arr = [3, 7, 3];
let K = 2;

// Function call
let result = minSum(arr, K);
document.write(result);

// This code is contributed by rakeshsahni

</script>```

## PHP

```<?php

// Function to find the minimum sum
function minSum(\$nums, \$k)
{
\$smallestUnsetBit = array();

// Iterate over the elements of
// given array
foreach (\$nums as \$num)
{
// Converting the number to its
// binary representation

for (\$i = 30; \$i >= 0; \$i--)
{
// Check if the ith bit is
// unset or not
if (\$s[\$i] == '0')
{
// Push ith unset bit
// into smallestUnsetBit
array_push(\$smallestUnsetBit, 30 - \$i);
}
}
}

// Sort the unsetbits in
// ascending order.
sort(\$smallestUnsetBit);

// Calculate the overall sum
// of given array
\$result = array_sum(\$nums);

\$i = 0;

// Add the overall effect of sum in
// the result by inverting the '0' bits.
while (\$k--)
{
\$result = (\$result + pow(2, \$smallestUnsetBit[\$i++])) % (PHP_INT_MAX);
}

// Return the result
return \$result % (PHP_INT_MAX);
}

// Driver Code
\$arr = array(3, 7, 3);
\$K = 2;

// Function call
\$result = minSum(\$arr, \$K);
echo \$result;
// This code is contributed by Kanishka Gupta
?>
```
Output

`21`

Time Complexity: O(N), where N is the length of the given array
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up