Ctrl K

Most Pieces With the Smallest AND Total

Medium
You are given an array values of non-negative integers. Cut it into contiguous pieces so that every element lands in exactly one piece. The **score** of a piece is the bitwise AND of all its elements. Among all cuts whose total score is as small as possible, find one with the most pieces and return how many pieces it has.
Example 1
values=[6, 1, 3, 4, 0, 5] → 3

The total cannot go below 0. Pieces [6, 1], [3, 4] and [0] all score 0; the last element 5 cannot reach 0 on its own, so it joins the last piece as [0, 5]. That makes 3 pieces.

Example 2
values=[7, 5, 13] → 1

The AND of the whole array is 7 & 5 & 13 = 5 > 0. Any split into several pieces sums to more than 5, so there is just one piece.

Example 3
values=[0, 0, 2] → 2
Constraints
  • 1 ≤ len(values) ≤ 10⁵
  • 0 ≤ values[i] ≤ 2·10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsBest Binary Rows After Flips MediumGroups of Four at the Cinema MediumBump One or Double All MediumDoubling for the Biggest OR MediumStrongest Product Team Medium
loading Python…
Input
values=[6, 1, 3, 4, 0, 5]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 101 tests on the server, hidden ones included.