Skip to content

Commit e39ae14

Browse files
authored
Create 3022-minimize-or-of-remaining-elements-using-operations.js
1 parent 621186f commit e39ae14

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
var minOrAfterOperations = function(nums, k) {
7+
let n = nums.length; //length of the array
8+
let res = 0; //this will contain the 'or' of all final elements of array
9+
10+
//Iterating from MSB to LSB
11+
for (let j = 30; j >= 0; j--)
12+
{
13+
let cnt = 0; //count of elements which have 0 at jth bit
14+
15+
//we will do & of all elements and store it here in 'cur' variable
16+
let cur = (1 << 30) - 1; //this is basically all last 30 bits set to 1
17+
18+
let target = res | ((1 << j) - 1); //jth bit is set 0 here, and bits from 0 to (j-1)th index are set to 1
19+
20+
for (let x of nums)
21+
{
22+
cur &= x;
23+
if ((cur | target) == target)
24+
{
25+
cnt++;
26+
cur = (1 << 30) - 1;
27+
}
28+
}
29+
30+
//we have to keep the jth bit if (n-cnt) is greater than k otherwise we can remove jth bit in less than or equal to k operations
31+
if (n - cnt > k)
32+
{
33+
res |= (1 << j);
34+
}
35+
}
36+
return res;
37+
};

0 commit comments

Comments
 (0)