Hint: Use DP. States would be: **current position, number of bars left, last-placed bar**

Solution:

Code complexity **(N^2)*(B) = 10^8**. A better solution might be available.

```
public static long solve(int idx, int b, long[] arr, long xor, int len, int last, long[][][] dp) {
if (idx == arr.length) {
if (b == 0) {
return xor * (len - 1); // final segment value
} else {
return Long.MAX_VALUE; // invalid state
}
}
// dp[idx][b][last] is the minimum value you can get from segment
// [idx,arr.length] when you have 'b' bars to place and the last bar was place
// placed at index 'last'
if (dp[idx][b][last] != -1) {
return dp[idx][b][last];
}
long placeBar = Long.MAX_VALUE;
if (b > 0) {
long myVal = (xor ^ arr[idx]) * len;
long restVal = solve(idx + 1, b - 1, arr, 0, 1, idx, dp);
if (restVal != Long.MAX_VALUE) {
placeBar = myVal + restVal;
}
}
long notPlaceBar = solve(idx + 1, b, arr, xor ^ arr[idx], len + 1, last, dp);
return dp[idx][b][last] = Math.min(placeBar, notPlaceBar);
}
```