```java
public int minOperationsMaxProfit(int[] customers, int boardingCost, int runningCost) {
    int waiting = 0;
    int profit = 0;
    int max_profit = 0;
    int rotations = 0;
    int result = -1;

    for (int i = 0; i < customers.length || waiting > 0; ++i) {
        if (i < customers.length) {
            waiting += customers[i];
        }
        int boarding = Math.min(waiting, 4);
        waiting -= boarding;
        profit += boarding * boardingCost - runningCost;

        if (profit > max_profit) {
            max_profit = profit;
            result = rotations + 1;
        }
        rotations++;
    }
    return result;
}
```

customers = \[8,3\], boardingCost = 5, runningCost = 6

```python
def minOperationsMaxProfit(customers, boardingCost, runningCost):
    waiting = 0
    profit = 0
    max_profit = 0
    rotations = 0
    result = -1

    for i in range(len(customers) + sum(customers)):
        if i < len(customers):
            waiting += customers[i]
        boarding = min(waiting, 4)
        waiting -= boarding
        profit += boarding * boardingCost - runningCost

        if profit > max_profit:
            max_profit = profit
            result = rotations + 1
        rotations += 1

    return result
```


```cpp
#include <vector>

int maximumRequests(int n, std::vector<std::vector<int>>& requests) {
    int req_size = requests.size();
    int max_requests = 0;

    for (int i = 0; i < (1 << req_size); ++i) {
        std::vector<int> net_transfers(n, 0);
        int count = 0;

        for (int j = 0; j < req_size; ++j) {
            if (i & (1 << j)) {
                net_transfers[requests[j][0]]--;
                net_transfers[requests[j][1]]++;
                count++;
            }
        }

        bool valid = true;
        for (int val : net_transfers) {
            if (val) {
                valid = false;
                break;
            }
        }

        if (valid)
            max_requests = std::max(max_requests, count);
    }

    return max_requests;
}
```

 5
Explantion: Let's see the requests:
From building 0 we have employees x and y and both want to move to building 1.
From building 1 we have employees a and b and they want to move to buildings 2 and 0 respectively.
From building 2 we have employee z and they want to move to building 0.
From building 3 we have employee c and they want to move to building 4.
From building 4 we don't have any requests.
We can achieve the requests of users x and b by swapping their places.
We can achieve the requests of users y, a and z by swapping the places in the 3 buildings.

```python
def maximumRequests(n, requests):
    req_size = len(requests)
    max_requests = 0

    for i in range(1 << req_size):
        net_transfers = [0] * n
        count = 0

        for j in range(req_size):
            if i & (1 << j):
                net_transfers[requests[j][0]] -= 1
                net_transfers[requests[j][1]] += 1
                count += 1

        valid = all(val == 0 for val in net_transfers)

        if valid:
            max_requests = max(max_requests, count)

    return max_requests
```


```python
def busiestServers(k, arrival, load):
    server_status = [-1] * k
    server_request_count = [0] * k

    for i in range(len(arrival)):
        index = i % k
        for _ in range(k):
            if server_status[index] <= arrival[i]:
                server_status[index] = arrival[i] + load[i]
                server_request_count[index] += 1
                break
            index = (index + 1) % k

    max_requests = max(server_request_count)
    return [i for i in range(k) if server_request_count[i] == max_requests]
```

```cpp
#include <vector>
using namespace std;

vector<int> busiestServers(int k, vector<int>& arrival, vector<int>& load) {
    vector<int> server_status(k, -1); // -1 means available
    vector<int> server_request_count(k, 0);

    for (int i = 0; i < arrival.size(); i++) {
        int index = i % k;
        for (int j = 0; j < k; j++) {
            if (server_status[index] <= arrival[i]) {
                server_status[index] = arrival[i] + load[i];
                server_request_count[index]++;
                break;
            }
            index = (index + 1) % k;
        }
    }

    int max_requests = *max_element(server_request_count.begin(), server_request_count.end());
    vector<int> busiest_servers;
    for (int i = 0; i < k; i++) {
        if (server_request_count[i] == max_requests) {
            busiest_servers.push_back(i);
        }
    }
    return busiest_servers;
}
```


```cpp
int specialArray(vector<int>& nums) {
    int max_val = *max_element(nums.begin(), nums.end());
    for (int x = 1; x <= max_val; ++x) {
        int count = 0;
        for (int num : nums) {
            if (num >= x) count++;
        }
        if (count == x) return x;
    }
    return -1;
}
```

```java
public int specialArray(int[] nums) {
    int max_val = Arrays.stream(nums).max().orElse(0);
    for (int x = 1; x <= max_val; ++x) {
        int count = 0;
        for (int num : nums) {
            if (num >= x) count++;
        }
        if (count == x) return x;
    }
    return -1;
}
```


```python
from collections import deque

class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def is_even_odd_tree(root):
    if not root:
        return False

    q = deque([root])
    level = 0

    while q:
        size = len(q)
        prev_val = 0 if level % 2 == 0 else 10**6 + 1

        for _ in range(size):
            curr = q.popleft()

            if ((level % 2 == 0 and (curr.val % 2 == 0 or curr.val <= prev_val)) or
                (level % 2 != 0 and (curr.val % 2 != 0 or curr.val >= prev_val))):
                return False

            prev_val = curr.val

            if curr.left:
                q.append(curr.left)
            if curr.right:
                q.append(curr.right)

        level += 1

    return True
```

true false false true true true true false true false true true true true true true false true true false true true true true true true false

```java
import java.util.LinkedList;
import java.util.Queue;

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
}

public boolean isEvenOddTree(TreeNode root) {
    if (root == null) return false;

    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int level = 0;

    while (!queue.isEmpty()) {
        int size = queue.size();
        int prevVal = (level % 2 == 0) ? 0 : 1000001;

        for (int i = 0; i < size; ++i) {
            TreeNode curr = queue.poll();

            if ((level % 2 == 0 && (curr.val % 2 == 0 || curr.val <= prevVal)) ||
                (level % 2 != 0 && (curr.val % 2 != 0 || curr.val >= prevVal))) {
                return false;
            }

            prevVal = curr.val;

            if (curr.left != null) queue.offer(curr.left);
            if (curr.right != null) queue.offer(curr.right);
        }

        level++;
    }

    return true;
}
```


```java
import java.util.HashSet;
import java.util.Set;

public boolean isPathCrossing(String path) {
    Set<String> visited = new HashSet<>();
    int x = 0, y = 0;
    visited.add(x + "," + y);
    for (char dir : path.toCharArray()) {
        if (dir == 'N') y++;
        else if (dir == 'S') y--;
        else if (dir == 'E') x++;
        else if (dir == 'W') x--;
        String location = x + "," + y;
        if (visited.contains(location)) return true;
        visited.add(location);
    }
    return false;
}
```

True True True True True True True True True True True True True True True True True True True True True True True

```python
def is_path_crossing(path: str) -> bool:
    visited = {(0, 0)}
    x, y = 0, 0
    for dir in path:
        if dir == 'N': y += 1
        elif dir == 'S': y -= 1
        elif dir == 'E': x += 1
        elif dir == 'W': x -= 1
        if (x, y) in visited: return True
        visited.add((x, y))
    return False
```


```java
import java.util.Arrays;

class Solution {
    public int numSubseq(int[] nums, int target) {
        int n = nums.length;
        int mod = 1000000007;

        Arrays.sort(nums);

        long[] power = new long[n];
        power[0] = 1;
        for (int i = 1; i < n; ++i) {
            power[i] = (power[i - 1] * 2) % mod;
        }

        int ans = 0;
        int r = n;

        for (int l = 0; l < n; ++l) {
            while (r > l && nums[l] + nums[r - 1] > target) {
                --r;
            }

            ans = (ans + (int)power[r - l]) % mod;
        }

        return ans;
    }
}
```

```cpp
#include <algorithm>
#include <vector>

int numSubseq(std::vector<int>& nums, int target) {
    int n = nums.size();
    int mod = 1e9 + 7;

    std::sort(nums.begin(), nums.end());

    std::vector<long long> power(n, 1);
    for (int i = 1; i < n; ++i) {
        power[i] = (power[i - 1] * 2) % mod;
    }

    int ans = 0;
    int r = n;
    for (int l = 0; l < n; ++l) {
        while (r > l && nums[l] + nums[r - 1] > target) {
            --r;
        }

        ans = (ans + power[r - l]) % mod;
    }

    return ans;
}
```


```python
def numSubmat(mat):
    m, n = len(mat), len(mat[0])
    dp = [[0] * n for _ in range(m)]
    count = 0

    for i in range(m):
        for j in range(n):
            if mat[i][j] == 1:
                dp[i][j] = (1 if j == 0 else dp[i][j - 1] + 1)
                minWidth = dp[i][j]
                for k in range(i, -1, -1):
                    minWidth = min(minWidth, dp[k][j])
                    count += minWidth

    return count
```

```java
public int numSubmat(int[][] mat) {
    int m = mat.length, n = mat[0].length;
    int[][] dp = new int[m][n];
    int count = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (mat[i][j] == 1) {
                dp[i][j] = (j == 0) ? 1 : dp[i][j - 1] + 1;
                int minWidth = dp[i][j];
                for (int k = i; k >= 0; k--) {
                    minWidth = Math.min(minWidth, dp[k][j]);
                    count += minWidth;
                }
            }
        }
    }
    return count;
}
```


```python
def get_min_dist_sum(positions: List[List[int]]) -> float:
    x, y = 0, 0
    n = len(positions)
    for pos in positions:
        x += pos[0]
        y += pos[1]
    x /= n
    y /= n
    return x
```

```cpp
#include <vector>
#include <algorithm>
#include <cmath>

double getMinDistSum(std::vector<std::vector<int>>& positions) {
    double x = 0;
    double y = 0;
    for (const auto& pos : positions) {
        x += pos[0];
        y += pos[1];
    }
    int n = positions.size();
    x /= n;
    y /= n;
    return x;
}
```


```python
def canFormArray(arr, pieces):
    map = {piece[0]: piece for piece in pieces}

    i = 0
    while i < len(arr):
        if arr[i] not in map:
            return False
        piece = map[arr[i]]
        for num in piece:
            if num != arr[i]:
                return False
            i += 1
    return True
```

true true true true true true true true true true true true true false true true true true true true true true true true true true true true true true true true true true true true true true true true false

```cpp
#include <vector>
#include <unordered_map>

bool canFormArray(std::vector<int>& arr, std::vector<std::vector<int>>& pieces) {
    std::unordered_map<int, std::vector<int>> map;
    for (auto& piece : pieces) {
        map[piece[0]] = piece;
    }

    int i = 0;
    while (i < arr.size()) {
        if (map.find(arr[i]) == map.end()) {
            return false;
        }
        std::vector<int>& piece = map[arr[i]];
        for (int j = 0; j < piece.size(); ++j) {
            if (piece[j] != arr[i]) {
                return false;
            }
            ++i;
        }
    }
    return true;
}
```


```cpp
int countVowelStrings(int n) {
    vector<int> dp = {1, 1, 1, 1, 1};
    for (int i = 2; i <= n; i++) {
        for (int j = 3; j >= 0; j--) {
            dp[j] = dp[j] + dp[j + 1];
        }
    }
    return accumulate(dp.begin(), dp.end(), 0);
}
```

```java
public int countVowelStrings(int n) {
    int[] dp = {1, 1, 1, 1, 1};
    for (int i = 2; i <= n; i++) {
        for (int j = 3; j >= 0; j--) {
            dp[j] = dp[j] + dp[j + 1];
        }
    }
    return Arrays.stream(dp).sum();
}
```


```java
import java.util.*;

public int minimumJumps(int[] forbidden, int a, int b, int x) {
    Set<Integer> forbidden_positions = new HashSet<>();
    for (int f : forbidden) {
        forbidden_positions.add(f);
    }
    Queue<int[]> q = new LinkedList<>();
    q.add(new int[]{0, 0, 0});
    Set<String> visited = new HashSet<>();
    visited.add("0,0");
    while (!q.isEmpty()) {
        int[] curr = q.poll();
        int pos = curr[0];
        int steps = curr[1];
        int backward = curr[2];
        if (pos == x) return steps;
        int forward_pos = pos + a;
        int backward_pos = pos - b;
        if (forward_pos <= 6000 && !forbidden_positions.contains(forward_pos) && !visited.contains(forward_pos + ",0")) {
            visited.add(forward_pos + ",0");
            q.add(new int[]{forward_pos, steps + 1, 0});
        }
        if (backward == 0 && backward_pos > 0 && !forbidden_positions.contains(backward_pos) && !visited.contains(backward_pos + ",1")) {
            visited.add(backward_pos + ",1");
            q.add(new int[]{backward_pos, steps + 1, 1});
        }
    }
    return -1;
}
```

```python
from collections import deque

def minimumJumps(forbidden, a, b, x):
    forbidden_positions = set(forbidden)
    q = deque([(0, 0, 0)])
    visited = {(0, 0)}
    while q:
        pos, steps, backward = q.popleft()
        if pos == x:
            return steps
        forward_pos = pos + a
        backward_pos = pos - b
        if forward_pos <= 6000 and forward_pos not in forbidden_positions and (forward_pos, 0) not in visited:
            visited.add((forward_pos, 0))
            q.append((forward_pos, steps + 1, 0))
        if backward == 0 and backward_pos > 0 and backward_pos not in forbidden_positions and (backward_pos, 1) not in visited:
            visited.add((backward_pos, 1))
            q.append((backward_pos, steps + 1, 1))
    return -1
```


```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public boolean canDistribute(int[] nums, int[] quantity) {
    Map<Integer, Integer> counts = new HashMap<>();
    for (int num : nums) {
        counts.put(num, counts.getOrDefault(num, 0) + 1);
    }

    List<Integer> values = new ArrayList<>(counts.values());
    Integer[] quantityArray = new Integer[quantity.length];
    for (int i = 0; i < quantity.length; i++) {
        quantityArray[i] = quantity[i];
    }
    Arrays.sort(quantityArray, Collections.reverseOrder());

    return dfs(0, values, quantityArray);
}

private boolean dfs(int index, List<Integer> values, Integer[] quantityArray) {
    if (index == quantityArray.length) {
        return true;
    }
    for (int i = 0; i < values.size(); i++) {
        if (values.get(i) >= quantityArray[index]) {
            values.set(i, values.get(i) - quantityArray[index]);
            if (dfs(index + 1, values, quantityArray)) return true;
            values.set(i, values.get(i) + quantityArray[index]);
        }
    }
    return false;
}
```

True True True True True True True True True True True True True True True True True True False True True True True False True True True True True True True True True True False False False True True False False True True True True False True True

```python
from collections import Counter

def canDistribute(nums, quantity):
    counts = Counter(nums)
    values = list(counts.values())
    quantity.sort(reverse=True)

    def dfs(index, values):
        if index == len(quantity):
            return True
        for i in range(len(values)):
            if values[i] >= quantity[index]:
                values[i] -= quantity[index]
                if dfs(index + 1, values):
                    return True
                values[i] += quantity[index]
        return False

    return dfs(0, values)
```


```java
public int numberOfFairs(int[] nums) {
    int even_sum = 0, odd_sum = 0, l_even = 0, l_odd = 0, count = 0;
    for (int i = 0; i < nums.length; ++i) {
        if (i % 2 == 0) even_sum += nums[i];
        else odd_sum += nums[i];
    }
    for (int i = 0; i < nums.length; ++i) {
        if (i % 2 == 0) {
            even_sum -= nums[i];
            if (l_even + odd_sum == l_odd + even_sum) ++count;
            l_even += nums[i];
        } else {
            odd_sum -= nums[i];
            if (l_even + odd_sum == l_odd + even_sum) ++count;
            l_odd += nums[i];
        }
    }
    return count;
}
```

```python
def numberOfFairs(nums):
    even_sum = sum(nums[0::2])
    odd_sum = sum(nums[1::2])
    l_even = l_odd = count = 0
    for i, num in enumerate(nums):
        if i % 2 == 0:
            even_sum -= num
            if l_even + odd_sum == l_odd + even_sum:
                count += 1
            l_even += num
        else:
            odd_sum -= num
            if l_even + odd_sum == l_odd + even_sum:
                count += 1
            l_odd += num
    return count
```


```python
def minimumEffort(tasks):
    tasks.sort(key=lambda task: task[1] - task[0], reverse=True)
    ans, sum_energy = 0, 0
    for task in tasks:
        ans = max(ans, sum_energy + task[1])
        sum_energy += task[0]
    return ans
```

```cpp
int minimumEffort(vector<vector<int>>& tasks) {
    sort(tasks.begin(), tasks.end(), [](vector<int>& a, vector<int>& b) {
        return a[1] - a[0] > b[1] - b[0];
    });
    int ans = 0, sum = 0;
    for (auto& task : tasks) {
        ans = max(ans, sum + task[1]);
        sum += task[0];
    }
    return ans;
}
```


```cpp
int longestAwesomeSubstring(std::string s) {
    int n = s.length();
    int maxLen = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j <= n; ++j) {
            std::string substr = s.substr(i, j - i);
            if (isAwesome(substr)) {
                maxLen = std::max(maxLen, j - i);
            }
        }
    }
    return maxLen;
}

bool isAwesome(std::string s) {
    int odd_count = 0;
    int freq[26] = {0};
    for (char c : s) {
        freq[c - 'a']++;
    }
    for (int i = 0; i < 26; i++) {
        if (freq[i] % 2 == 1) {
            odd_count++;
        }
    }
    return (odd_count <= 1);
}
```

```java
int longestAwesomeSubstring(String s) {
    int n = s.length();
    int maxLen = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j <= n; ++j) {
            String substr = s.substring(i, j);
            if (isAwesome(substr)) {
                maxLen = Math.max(maxLen, j - i);
            }
        }
    }
    return maxLen;
}

boolean isAwesome(String s) {
    int odd_count = 0;
    int[] freq = new int[26];
    for (char c : s.toCharArray()) {
        freq[c - 'a']++;
    }
    for (int i = 0; i < 26; i++) {
        if (freq[i] % 2 == 1) {
            odd_count++;
        }
    }
    return (odd_count <= 1);
}
```


```python
def minCost(n, cuts):
    cuts = [0] + cuts + [n]
    cuts.sort()
    size = len(cuts)
    dp = [[0] * size for _ in range(size)]

    for len in range(2, size):
        for i in range(size - len):
            j = i + len
            dp[i][j] = float('inf')
            for k in range(i + 1, j):
                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + cuts[j] - cuts[i])

    return dp[0][size - 1]
```

```cpp
#include <vector>
#include <algorithm>
#include <limits.h>

int minCost(int n, std::vector<int>& cuts) {
    cuts.push_back(0);
    cuts.push_back(n);
    std::sort(cuts.begin(), cuts.end());
    int size = cuts.size();
    std::vector<std::vector<int>> dp(size, std::vector<int>(size, 0));

    for (int len = 2; len < size; ++len) {
        for (int i = 0; i < size - len; ++i) {
            int j = i + len;
            dp[i][j] = INT_MAX;
            for (int k = i + 1; k < j; ++k) {
                dp[i][j] = std::min(dp[i][j], dp[i][k] + dp[k][j] + cuts[j] - cuts[i]);
            }
        }
    }

    return dp[0][size - 1];
}
```


```cpp
int minimumMountainRemovals(vector<int>& nums) {
    int n = nums.size();
    vector<int> left(n), right(n);
    for (int i = 1; i < n; ++i) {
        left[i] = left[i - 1] + (nums[i] > nums[i - 1]);
        right[n - i - 1] = right[n - i] + (nums[n - i - 1] > nums[n - i]);
    }
    int ans = n - 3;
    for (int i = 1; i < n - 1; ++i) {
        ans = min(ans, n - 1 - left[i] - right[i]);
    }
    return ans;
}
```

```java
public int minimumMountainRemovals(int[] nums) {
    int n = nums.length;
    int[] left = new int[n], right = new int[n];
    for (int i = 1; i < n; ++i) {
        left[i] = left[i - 1] + (nums[i] > nums[i - 1] ? 1 : 0);
        right[n - i - 1] = right[n - i] + (nums[n - i - 1] > nums[n - i] ? 1 : 0);
    }
    int ans = n - 3;
    for (int i = 1; i < n - 1; ++i) {
        ans = Math.min(ans, n - 1 - left[i] - right[i]);
    }
    return ans;
}
```


```cpp
int maximumWealth(vector<vector<int>>& accounts) {
    int max_wealth = 0;
    for (auto& customer : accounts) {
        int wealth = 0;
        for (int account : customer) {
            wealth += account;
        }
        max_wealth = max(max_wealth, wealth);
    }
    return max_wealth;
}
```

```java
public int maximumWealth(int[][] accounts) {
    int maxWealth = 0;
    for (int[] customer : accounts) {
        int wealth = 0;
        for (int account : customer) {
            wealth += account;
        }
        maxWealth = Math.max(maxWealth, wealth);
    }
    return maxWealth;
}
```


```python
def num_ways(s: str) -> int:
    number_of_ones = s.count('1')
    if number_of_ones % 3 != 0:
        return 0

    target = number_of_ones // 3
    if target == 0:
        n = len(s)
        return ((n - 1) * (n - 2) // 2) % 1000000007

    ones_so_far1, ones_so_far2 = 0, 0
    way1, way2 = 0, 0
    for c in s:
        if c == '1':
            ones_so_far1 += 1
            if ones_so_far1 == target:
                way1 += 1
                ones_so_far1 = 0

            ones_so_far2 += 1
            if ones_so_far2 == target * 2:
                way2 += 1
                ones_so_far2 = 0

    return (way1 * way2) % 1000000007
```

```java
public int numWays(String s) {
    int numberOfOnes = 0;
    for (char c : s.toCharArray()) {
        if (c == '1') numberOfOnes++;
    }
    if (numberOfOnes % 3 != 0) return 0;

    int target = numberOfOnes / 3;
    if (target == 0) {
        long n = s.length();
        return (int) ((n - 1) * (n - 2) / 2 % 1000000007);
    }

    int onesSoFar1 = 0, onesSoFar2 = 0;
    long way1 = 0, way2 = 0;
    for (char c : s.toCharArray()) {
        if (c == '1') {
            onesSoFar1++;
            if (onesSoFar1 == target) {
                way1++;
                onesSoFar1 = 0;
            }

            onesSoFar2++;
            if (onesSoFar2 == target * 2) {
                way2++;
                onesSoFar2 = 0;
            }
        }
    }

    return (int) (way1 * way2 % 1000000007);
}
```


```java
public int stoneGameV(int[] stoneValue) {
    int n = stoneValue.length;
    int[][] memo = new int[n][n];
    return maxScore(stoneValue, 0, n - 1, memo);
}

private int maxScore(int[] stoneValue, int start, int end, int[][] memo) {
    if (start == end) return 0;
    if (memo[start][end] != 0) return memo[start][end];

    int leftSum = 0, rightSum = 0;
    for (int i = start; i < end; ++i) {
        leftSum += stoneValue[i];
        rightSum = 0;
        for (int j = i + 1; j <= end; ++j)
            rightSum += stoneValue[j];

        if (leftSum > rightSum)
            memo[start][end] = Math.max(memo[start][end], rightSum + maxScore(stoneValue, i + 1, end, memo));
        else if (leftSum < rightSum)
            memo[start][end] = Math.max(memo[start][end], leftSum + maxScore(stoneValue, start, i, memo));
        else
            memo[start][end] = Math.max(memo[start][end], leftSum + Math.max(maxScore(stoneValue, start, i, memo), maxScore(stoneValue, i + 1, end, memo)));
    }
    return memo[start][end];
}
```

```cpp
#include <vector>
#include <algorithm>
using namespace std;

int maxScore(const vector<int>& stoneValue, int start, int end, vector<vector<int>>& memo) {
    if (start == end) return 0;
    if (memo[start][end] != -1) return memo[start][end];

    int leftSum = 0, rightSum = 0;
    for (int i = start; i < end; ++i) {
        leftSum += stoneValue[i];
        rightSum = 0;
        for (int j = i + 1; j <= end; ++j)
            rightSum += stoneValue[j];

        if (leftSum > rightSum)
            memo[start][end] = max(memo[start][end], rightSum + maxScore(stoneValue, i + 1, end, memo));
        else if (leftSum < rightSum)
            memo[start][end] = max(memo[start][end], leftSum + maxScore(stoneValue, start, i, memo));
        else
            memo[start][end] = max(memo[start][end], leftSum + max(maxScore(stoneValue, start, i, memo), maxScore(stoneValue, i + 1, end, memo)));
    }
    return memo[start][end];
}

int stoneGameV(vector<int>& stoneValue) {
    int n = stoneValue.size();
    vector<vector<int>> memo(n, vector<int>(n, -1));
    return maxScore(stoneValue, 0, n - 1, memo);
}
```


```cpp
#include <vector>
#include <algorithm>

int stoneGameVI(std::vector<int>& aliceValues, std::vector<int>& bobValues) {
    int n = aliceValues.size();
    std::vector<std::pair<int, int>> diff;
    for (int i = 0; i < n; ++i) {
        diff.push_back({aliceValues[i] + bobValues[i], i});
    }

    std::sort(diff.rbegin(), diff.rend());
    int aliceSum = 0, bobSum = 0;
    for (int i = 0; i < n; ++i) {
        if (i % 2 == 0) {
            aliceSum += aliceValues[diff[i].second];
        } else {
            bobSum += bobValues[diff[i].second];
        }
    }

    return (aliceSum == bobSum) ? 0 : ((aliceSum > bobSum) ? 1 : -1);
}
```

aliceValues = \[1,3\], bobValues = \[2,1\]

```python
def stoneGameVI(aliceValues, bobValues):
    n = len(aliceValues)
    diff = sorted([(aliceValues[i] + bobValues[i], i) for i in range(n)], reverse=True)

    aliceSum, bobSum = 0, 0
    for i in range(n):
        if i % 2 == 0:
            aliceSum += aliceValues[diff[i][1]]
        else:
            bobSum += bobValues[diff[i][1]]

    return 0 if aliceSum == bobSum else (1 if aliceSum > bobSum else -1)
```


```cpp
int min_trips(vector<vector<int>> &boxes, int portsCount, int maxBoxes, int maxWeight) {
    int trips = 0, idx = 0, n = boxes.size();
    while (idx < n) {
        int curr_limit = maxWeight, prev_port = 0;
        for (int count = 0; count < maxBoxes && idx < n; ++idx) {
            if (boxes[idx][1] <= curr_limit) {
                if (prev_port != boxes[idx][0]) {
                    prev_port = boxes[idx][0];
                    ++trips;
                }
                curr_limit -= boxes[idx][1];
                ++count;
            }
        }
        ++trips;
    }
    return trips;
}
```

```python
def min_trips(boxes, portsCount, maxBoxes, maxWeight):
    trips = 0
    idx = 0
    n = len(boxes)
    while idx < n:
        curr_limit = maxWeight
        prev_port = 0
        count = 0
        while count < maxBoxes and idx < n:
            if boxes[idx][1] <= curr_limit:
                if prev_port != boxes[idx][0]:
                    prev_port = boxes[idx][0]
                    trips += 1
                curr_limit -= boxes[idx][1]
                count += 1
                idx += 1
            else:
                break
        trips += 1
    return trips
```


```cpp
int getMaxLen(vector<int>& nums) {
    int maxLength = 0, currentLen = 0, currentNegLen = 0;

    for (int num : nums) {
        if (num > 0) {
            ++currentLen;
            if (currentNegLen > 0) ++currentNegLen;
        } else if (num < 0) {
            int tmp = currentLen;
            currentLen = currentNegLen;
            currentNegLen = tmp + 1;
        } else {
            currentLen = 0;
            currentNegLen = 0;
        }
        maxLength = max(maxLength, currentLen);
    }

    return maxLength;
}
```

```python
def getMaxLen(nums):
    maxLength = currentLen = currentNegLen = 0

    for num in nums:
        if num > 0:
            currentLen += 1
            if currentNegLen > 0:
                currentNegLen += 1
        elif num < 0:
            currentLen, currentNegLen = currentNegLen, currentLen + 1
        else:
            currentLen = currentNegLen = 0
        maxLength = max(maxLength, currentLen)

    return maxLength
```


```python
def numTrees(n: int) -> int:
    dp = [0] * (n + 1)
    dp[0] = 1
    dp[1] = 1

    for i in range(2, n + 1):
        for j in range(i):
            dp[i] += dp[j] * dp[i - 1 - j]
            dp[i] %= (10**9 + 7)

    return dp[n]
```


```java
import java.util.*;

public class Solution {
    public boolean[] distanceLimitedPathsExist(int n, int[][] edgeList, int[][] queries) {
        Map<Integer, List<int[]>> graph = new HashMap<>();

        for (int[] edge : edgeList) {
            graph.putIfAbsent(edge[0], new ArrayList<>());
            graph.putIfAbsent(edge[1], new ArrayList<>());
            graph.get(edge[0]).add(new int[]{edge[1], edge[2]});
            graph.get(edge[1]).add(new int[]{edge[0], edge[2]});
        }

        boolean[] answer = new boolean[queries.length];
        for (int i = 0; i < queries.length; i++) {
            int pj = queries[i][0], qj = queries[i][1], limitj = queries[i][2];

            Queue<int[]> q = new LinkedList<>();
            q.add(new int[]{pj, 0});
            boolean[] visited = new boolean[n];
            visited[pj] = true;

            while (!q.isEmpty()) {
                int[] curr = q.poll();

                for (int[] next : graph.getOrDefault(curr[0], new ArrayList<>())) {
                    if (curr[1] + next[1] < limitj) {
                        if (next[0] == qj) {
                            answer[i] = true;
                            break;
                        }
                        if (!visited[next[0]]) {
                            visited[next[0]] = true;
                            q.add(new int[]{next[0], curr[1] + next[1]});
                        }
                    }
                }
                if (answer[i])
                    break;
            }
        }
        return answer;
    }
}
```

[True, False]
[False, False]
[False, False]
[False, False]
[False, False]
[True, False]
[True, False]
[True, False]
[True, True]
[False, False]
[True, True]
[False, False]
[True, True]
[False, False]
[False, False]
[False, False]
[True, True]
[False, False]
[True, False]
[False, False]
[True, False]
[False, False]
[False, False]
[False, False]
[False, False]
[True, False]
[True, False]
[False, False]
[False, True]
[False, False]
[False, False]
[False, False]
[False, False]
[False, False]
[True, False]
[False, False]
[True, True]
[False, False]
[False, False]
[True, False]
[False, False]
[False, False]
[False, False]
[False, True]

```python
from collections import defaultdict, deque

def distanceLimitedPathsExist(n, edgeList, queries):
    graph = defaultdict(list)

    for u, v, dis in edgeList:
        graph[u].append((v, dis))
        graph[v].append((u, dis))

    answer = [False] * len(queries)
    for i, (pj, qj, limitj) in enumerate(queries):
        q = deque([(pj, 0)])
        visited = [False] * n
        visited[pj] = True

        while q:
            curr_node, curr_dist = q.popleft()

            for next_node, next_dist in graph[curr_node]:
                if curr_dist + next_dist < limitj:
                    if next_node == qj:
                        answer[i] = True
                        break
                    if not visited[next_node]:
                        visited[next_node] = True
                        q.append((next_node, curr_dist + next_dist))
            if answer[i]:
                break

    return answer
```


```cpp
#include <string>

std::string modifyString(std::string s) {
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '?') {
            for (char c = 'a'; c <= 'z'; c++) {
                if ((i - 1 < 0 || s[i - 1] != c) && (i + 1 >= s.size() || s[i + 1] != c)) {
                    s[i] = c;
                    break;
                }
            }
        }
    }
    return s;
}
```

abcabcabcabcabcab aa abcabcabcabcabcabcabcabcabcabcabc abcabcabcabcabcabcabcabcabcabcabcab a abcabcabcabcabcabcabc abcdefg abcabcabcabcabcabc abccba abcabcabc abcabcabcabcabcabcabcabcabca ab abcabcabcabcabca abcabcabcabcabcabcabcabcabcabcab abcabcabca abcabcabcabcabcabca bcbcbcbc abcabcabcabc abcabcabcabcabcabcabcabcabcabcabcabc aabbaba abcabcabcabcabcabcabcabc abcabcabcabcabc abcabcabcabcabcabcabcab abcabcabcabcabcabcabcabcab aabbaba abcabcabcabcabcabcabcabcabcab abcabcabcabcabcabcabca abcabcabcabca aaa abcabcabcabcabcabcab bcbcbcb abcabcabcab abab abcabcabcabcab abcabcabcabcabcabcabcabcabcabca abcabcabcabcabcabcabcabcabcabcabca abcabc abc abcabcabcabcabcabcabcabcabcabc aabbaba aaabbb abcabcabcabcabcabcabcabcabc abcabcabcabcabcabcabcabca

abcabcabcabc a abcabcabcabcabcabcabcabcabcabca abcabcabcabcabcabcabc aabbaba abcabcabcabcabcabcabcabcab abcabcabcabcabcabca abcabcabcabcabcabcabcab abcabcabcabcabcabc abcabc abcabcabcabcabcabcabcabcabcabcab aaabbb abcabcabcabcabcabcabcabca ab abcabcabcabcabcabcabca abcabcabcabcabcabcabcabcabcab abcabcabcab aa abcabcabcabcabca abcabcabcabcabcabcabcabcabcabcabcabc abcabcabcabca aabbaba abcabcabcabcab abcabcabcabcabcabcab abcabcabcabcabcabcabcabcabcabcabc bcbcbcb aaa abcabcabcabcabcabcabcabcabcabcabca abcabcabcabcabcabcabcabcabc abcdefg abcabcabcabcabcab abab bcbcbcbc abcabcabc abcabcabca abccba aabbaba abcabcabcabcabc abcabcabcabcabcabcabcabcabcabc abcabcabcabcabcabcabcabcabcabcabcab abcabcabcabcabcabcabcabc abcabcabcabcabcabcabcabcabca abc

```python
def modifyString(s: str) -> str:
    s = list(s)
    for i in range(len(s)):
        if s[i] == '?':
            for c in range(ord('a'), ord('z') + 1):
                if (i - 1 < 0 or s[i - 1] != chr(c)) and (i + 1 >= len(s) or s[i + 1] != chr(c)):
                    s[i] = chr(c)
                    break
    return ''.join(s)
```


```python
def minMoves(nums, k):
    ones_pos = [i for i, x in enumerate(nums) if x == 1]
    to_move = [i_b - i_a for i_a, i_b in zip(range(k), ones_pos)]
    min_moves = sum(to_move[k // 2:])
    move = min_moves
    for left, right in zip(
        to_move[:-k],       # left "window" of k-sized sliding window
        to_move[k // 2 + 1:],  # right "window" of k-sized sliding window
    ):
        move += left - right
        min_moves = min(min_moves, move)
    return min_moves
```

```cpp
int minMoves(vector<int>& nums, int k) {
    vector<int> ones_pos;
    int moves = 0;
    for (int i = 0; i < nums.size(); i++) {
        if (nums[i] == 1) {
            ones_pos.push_back(i);
        }
    }
    for (int i = 0; i + k <= ones_pos.size(); i++) {
        int pos = ones_pos[i + k / 2];
        for (int j = i; j < i + k; j++) {
            moves += abs(ones_pos[j] - pos);
        }
    }
    return moves;
}
```


```cpp
#include <vector>
#include <algorithm>

int minCostConnectPoints(std::vector<std::vector<int>>& points) {
    int n = points.size();
    std::vector<int> cost(n);
    std::vector<bool> visited(n, false);
    std::fill(cost.begin(), cost.end(), INT_MAX);
    cost[0] = 0;

    int ans = 0;

    for (int i = 0; i < n; ++i) {
        int min_cost = INT_MAX;
        int cur_point = -1;
        for (int j = 0; j < n; ++j) {
            if (!visited[j] && cost[j] < min_cost) {
                min_cost = cost[j];
                cur_point = j;
            }
        }

        visited[cur_point] = true;
        ans += min_cost;

        for (int j = 0; j < n; ++j) {
            if (!visited[j]) {
                int new_cost = std::abs(points[cur_point][0] - points[j][0]) + std::abs(points[cur_point][1] - points[j][1]);
                cost[j] = std::min(cost[j], new_cost);
            }
        }
    }

    return ans;
}
```

```java
import java.util.Arrays;

public int minCostConnectPoints(int[][] points) {
    int n = points.length;
    int[] cost = new int[n];
    boolean[] visited = new boolean[n];
    Arrays.fill(cost, Integer.MAX_VALUE);
    cost[0] = 0;

    int ans = 0;

    for (int i = 0; i < n; i++) {
        int min_cost = Integer.MAX_VALUE;
        int cur_point = -1;
        for (int j = 0; j < n; j++) {
            if (!visited[j] && cost[j] < min_cost) {
                min_cost = cost[j];
                cur_point = j;
            }
        }

        visited[cur_point] = true;
        ans += min_cost;

        for (int j = 0; j < n; j++) {
            if (!visited[j]) {
                int new_cost = Math.abs(points[cur_point][0] - points[j][0]) + Math.abs(points[cur_point][1] - points[j][1]);
                cost[j] = Math.min(cost[j], new_cost);
            }
        }
    }

    return ans;
}
```


```python
def waysToSplit(nums):
    MOD = 10**9 + 7
    n = len(nums)
    prefixSum = [0] * (n + 1)
    for i in range(n):
        prefixSum[i + 1] = prefixSum[i] + nums[i]

    ans = 0
    left, right = 0, 0
    for mid in range(1, n - 1):
        while left + 1 < mid and prefixSum[left + 1] * 2 <= prefixSum[mid]:
            left += 1
        while right < mid or (right + 1 < n and prefixSum[right + 1] - prefixSum[mid] <= prefixSum[n] - prefixSum[right + 1]):
            right += 1
        if right >= mid and prefixSum[mid] - prefixSum[left] <= prefixSum[right] - prefixSum[mid]:
            ans = (ans + right - mid + 1) % MOD

    return ans
```

```cpp
int waysToSplit(vector<int>& nums) {
    int MOD = 1e9 + 7;
    int n = nums.size();
    vector<long long> prefixSum(n + 1, 0);
    for (int i = 0; i < n; i++) {
        prefixSum[i + 1] = prefixSum[i] + nums[i];
    }
    int ans = 0;
    int left = 0, right = 0;
    for (int mid = 1; mid < n - 1; mid++) {
        while (left + 1 < mid && prefixSum[left + 1] * 2 <= prefixSum[mid]) {
            left++;
        }
        while (right < mid || (right + 1 < n && prefixSum[right + 1] - prefixSum[mid] <= prefixSum[n] - prefixSum[right + 1])) {
            right++;
        }
        if (right >= mid && prefixSum[mid] - prefixSum[left] <= prefixSum[right] - prefixSum[mid]) {
            ans = (ans + right - mid + 1) % MOD;
        }
    }
    return ans;
}
```


```cpp
#include <vector>
#include <unordered_map>
using namespace std;

int minOperations(vector<int>& target, vector<int>& arr) {
    unordered_map<int, int> pos;
    for (int i = 0; i < target.size(); ++i) {
        pos[target[i]] = i;
    }

    vector<int> dp;
    for (const int& a : arr) {
        if (pos.find(a) != pos.end()) {
            auto idx = lower_bound(dp.begin(), dp.end(), pos[a]);
            if (idx == dp.end()) {
                dp.push_back(pos[a]);
            } else {
                *idx = pos[a];
            }
        }
    }
    return target.size() - dp.size();
}
```

```python
from bisect import bisect_left

def minOperations(target, arr):
    pos = {x: i for i, x in enumerate(target)}

    dp = []
    for a in arr:
        if a in pos:
            idx = bisect_left(dp, pos[a])
            if idx == len(dp):
                dp.append(pos[a])
            else:
                dp[idx] = pos[a]
    return len(target) - len(dp)
```


```cpp
vector<int> constructDistancedSequence(int n) {
    vector<int> res(2 * n - 1, 0);
    function<bool(int,int)> dfs = [&](int i, int unused){
        if (i == res.size()) return true;
        if (res[i]) return dfs(i + 1, unused);
        for (int num = n; num > 0; --num) {
            if ((unused >> num) & 1) {
                if (num == 1 || i + num < res.size() && !res[i + num]) {
                    res[i] = num;
                    if (num > 1) res[i + num] = num;
                    if (dfs(i + 1, unused ^ (1 << num))) return true;
                    res[i] = 0;
                    if (num > 1) res[i + num] = 0;
                }
            }
        }
        return false;
    };
    dfs(0, (1 << (n + 1)) - 2);
    return res;
}
```

```python
class Solution:
    def constructDistancedSequence(self, n: int) -> List[int]:
        res = [0] * (2 * n - 1)

        def backtrack(i, unused):
            if i == len(res):
                return True
            if res[i]:
                return backtrack(i + 1, unused)
            for num in range(n, 0, -1):
                if (unused >> num) & 1:
                    if num == 1 or (i + num < len(res) and not res[i + num]):
                        res[i] = num
                        if num > 1:
                            res[i + num] = num
                        if backtrack(i + 1, unused ^ (1 << num)):
                            return True
                        res[i] = 0
                        if num > 1:
                            res[i + num] = 0
            return False

        backtrack(0, (1 << (n + 1)) - 2)
        return res
```


```python
def check_ways(pairs):
    candidates = {}
    for x, y in pairs:
        candidates[x] = candidates.get(x, 0) + 1
        candidates[y] = candidates.get(y, 0) + 1

    root_count = sum(1 for v in candidates.values() if v == 1)
    return min(root_count, 2)
```

```cpp
#include <vector>
#include <unordered_map>

int checkWays(std::vector<std::vector<int>>& pairs) {
    std::unordered_map<int, int> candidates;
    for (const auto& pair : pairs) {
        ++candidates[pair[0]];
        ++candidates[pair[1]];
    }

    int rootCount = 0;
    for (const auto& candidate : candidates) {
        if (candidate.second == 1) {
            ++rootCount;
            if (rootCount > 1) {
                return 2;
            }
        }
    }

    return rootCount;
}
```


```python
def min_operations_max_profit(customers, boarding_cost, running_cost):
    rotations = waiting = on_board = profit = max_profit = max_rotations = 0
    while customers or waiting > 0:
        if customers:
            waiting += customers.pop(0)

        on_board = min(waiting, 4)
        waiting -= on_board
        profit += on_board * boarding_cost - running_cost
        rotations += 1

        if profit > max_profit:
            max_profit = profit
            max_rotations = rotations

    return max_rotations if max_profit > 0 else -1
```

```cpp
#include <algorithm>
#include <vector>
using namespace std;

int minOperationsMaxProfit(vector<int>& customers, int boardingCost, int runningCost) {
    int rotations = 0, waiting = 0, onBoard = 0, profit = 0, maxProfit = 0, maxRotations = 0;
    while (!customers.empty() || waiting > 0) {
        if (!customers.empty()) {
            waiting += customers.front();
            customers.erase(customers.begin());
        }

        onBoard = min(waiting, 4);
        waiting -= onBoard;
        profit += onBoard * boardingCost - runningCost;
        rotations++;

        if (profit > maxProfit) {
            maxProfit = profit;
            maxRotations = rotations;
        }
    }
    return maxProfit > 0 ? maxRotations : -1;
}
```


```python
def decode(encoded):
    n = len(encoded) + 1
    total_xor = 0

    for i in range(1, n + 1):
        total_xor ^= i

    non_first_xor = 0
    for i in range(1, n - 1, 2):
        non_first_xor ^= encoded[i]

    perm = [total_xor ^ non_first_xor]
    for i in range(1, n):
        perm.append(perm[-1] ^ encoded[i - 1])

    return perm
```

```cpp
#include <vector>

std::vector<int> decode(std::vector<int>& encoded) {
    int n = encoded.size() + 1;
    int totalXor = 0;
    for (int i = 1; i <= n; i++) {
        totalXor ^= i;
    }

    int nonFirstXor = 0;
    for (int i = 1; i < n - 1; i += 2) {
        nonFirstXor ^= encoded[i];
    }

    std::vector<int> perm(n);
    perm[0] = totalXor ^ nonFirstXor;

    for (int i = 1; i < n; i++) {
        perm[i] = perm[i - 1] ^ encoded[i - 1];
    }

    return perm;
}
```


```cpp
int minimumLength(string s) {
    if(s.empty()) return 0;
    int i = 0, j = s.length() - 1;
    while(i < j){
        if(s[i] != s[j]) break;
        char remove_char = s[i];
        while(i < s.length() && s[i] == remove_char) i++;
        while(j >= 0 && s[j] == remove_char) j--;
    }
    return max(0, j - i + 1);
}
```

aaccccbaba ab acababcabc babacbcabc a cabcabacba cabaabac cacac acababcbcb aabccabba cccbbbaa bcbcbcbabc aa cabcbaacbc babacabcac caaaccccb acbabcabcc abcabcabc babcbcbca cabcbabcac ca cbabcacbac babcaabcc bababcbabc bacacababc ca cbcacabacb acabcccbab acababcbca aaaa babcbacbac acabbaac aabccbaaa aabaa cababacaba babcbcbabc cbacbacabc baaacaba aaa acbabcabcb ca cabacaba bcbabcabbc acbcbacabc

```java
public int minimumLength(String s) {
    if(s.isEmpty()) return 0;
    int i = 0, j = s.length() - 1;
    while(i < j){
        if(s.charAt(i) != s.charAt(j)) break;
        char remove_char = s.charAt(i);
        while(i < s.length() && s.charAt(i) == remove_char) i++;
        while(j >= 0 && s.charAt(j) == remove_char) j--;
    }
    return Math.max(0, j - i + 1);
}
```


```python
def largest_merge(word1: str, word2: str) -> str:
    merge = []
    while word1 or word2:
        if word1 > word2:
            merge.append(word1[0])
            word1 = word1[1:]
        else:
            merge.append(word2[0])
            word2 = word2[1:]
    return ''.join(merge)
```

ghiabcdeabcd edcbaefgihjklmnopqrsabcde dcbaefgihabcde bCaCABA edcbaefgihjklmnabcde dcbaefgabcde edcbaefgihjkabcde edcbafabcde edcbaefgihjklmnopqrstuvwxyabcde abcabc edcbaefgihjklmnopqrstabcde defabc edcbaefgihjklmabcde za edcbaefgihjabcde edcbaefgihjklmnopqabcde fghabcdeabcde za edcbabcdea edcbaefgihjklmnopqrstuvwxabcde jklmnoabcde cbcabaaaaa opqrstabcde edcbaefghabcde edcbaefgihjklmnopqrstuabcde ba dddccc edcbaefgihjklmnopqrstuvabcde edcbaefgihjklmnoabcde abdcabcabcaba dcbaeabcde abc123 defabc bcdefabcde efgbcdeabcde ba cbcabaaaaa uvwxyzabcde edcbaefgihjklmnopqrabcde edcbaefgihjklmnopqrstuvwabcde edcbaefgihjklabcde edcbaefgihjklmnopabcde abcabc

```java
public String largestMerge(String word1, String word2) {
    StringBuilder result = new StringBuilder();
    while (!word1.isEmpty() || !word2.isEmpty()) {
        if (word1.compareTo(word2) > 0) {
            result.append(word1.charAt(0));
            word1 = word1.substring(1);
        } else {
            result.append(word2.charAt(0));
            word2 = word2.substring(1);
        }
    }
    return result.toString();
}
```


```java
public int[] decrypt(int[] code, int k) {
    int n = code.length;
    int[] result = new int[n];
    if (k == 0) return result;

    for (int i = 0; i < n; i++) {
        int sum = 0;
        for (int j = 1; j <= Math.abs(k); j++) {
            sum += k > 0 ? code[(i + j) % n] : code[(i - j + n) % n];
        }
        result[i] = sum;
    }
    return result;
}
```

```python
def decrypt(code, k):
    n = len(code)
    result = [0] * n
    if k == 0: return result

    for i in range(n):
        sum = 0
        for j in range(1, abs(k) + 1):
            sum += code[(i + j) % n] if k > 0 else code[(i - j + n) % n]
        result[i] = sum
    return result
```


```python
def count_homogenous(s: str) -> int:
    MOD = 1000000007
    count, total = 1, 0
    for i in range(1, len(s)):
        count = count + 1 if s[i] == s[i - 1] else 1
        total = (total + count) % MOD
    return (total + count) % MOD
```

aaaaaaa aa ab cccc cccccccccc dddd bbbb dddd ccccccc abcdefghi ccc b ab dd abcde aaaaaaaa c abc aaaaaaaa abcdefgh bbbbbbbb bbbbbbbbbb a aaaaaa cc aaa bbbbbbbb ccc cccccc aaaaaaaaaa ddd abcdefghi abcdefghij aaaaaaaaa abcde aa cccccccc abcabcabc cccc a d bbbb aaaaa bbb aaaaa bbbbbb a bbbbbbbbbb bb ddd ccccccccccc cccccccc bbbbbbb cccccccccc aaa bbbbb aaaaaaaaa aaa aaaaaaaaaa ccccccccc abcd abcdefg bbbbbb abc abcd b aaaaaa ccccccccc abcdefghij aaaa bbb aaaa cc bb aaaa cccccc abcdefg abc d c dd aa abcdef abbcccaa abcdef aaaaaaa abcdefgh bbbbbbb ccccccc ccccccccccc bbbbb

```java
public int countHomogenous(String s) {
    final int MOD = 1000000007;
    long count = 1;
    long total = 0;
    for (int i = 1; i < s.length(); ++i) {
        count = (s.charAt(i) == s.charAt(i - 1)) ? count + 1 : 1;
        total = (total + count) % MOD;
    }
    return (int) (total + count) % MOD;
}
```


```java
public int maxKRepeating(String sequence, String word) {
    int maxK = 0;
    int seqLength = sequence.length();
    int wordLength = word.length();
    for (int i = 0; i <= seqLength - wordLength; i++) {
        int k = 0;
        while (sequence.startsWith(repeat(word, k + 1), i)) {
            k++;
        }
        if (k > maxK) {
            maxK = k;
        }
    }
    return maxK;
}

private String repeat(String str, int count) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < count; i++) {
        sb.append(str);
    }
    return sb.toString();
}
```

```python
def max_k_repeating(sequence, word):
    max_k = 0
    seq_length = len(sequence)
    word_length = len(word)
    for i in range(seq_length - word_length + 1):
        k = 0
        while sequence[i:i + word_length * (k + 1)] == word * (k + 1):
            k += 1
        max_k = max(max_k, k)
    return max_k
```


```java
public int minimumMountainRemovals(int[] nums) {
    int n = nums.length;
    int[] left = new int[n], right = new int[n];
    for (int i = 0; i < n; ++i) {
        left[i] = lowerBound(Arrays.copyOfRange(left, 0, i), nums[i]);
        right[n - 1 - i] = lowerBound(reverse(Arrays.copyOfRange(right, n - 1 - i, n)), nums[n - 1 - i]);
    }
    int result = n;
    for (int i = 1; i < n - 1; ++i)
        result = Math.min(result, n - (left[i] + 1) - (right[i] + 1));

    return result;
}
```

```cpp
int minimumMountainRemovals(vector<int>& nums) {
    int n = nums.size();
    vector<int> left(n), right(n);
    for (int i = 0; i < n; ++i) {
        left[i] = lower_bound(left.begin(), left.begin() + i, nums[i]) - left.begin();
        right[n - 1 - i] = lower_bound(right.rbegin(), right.rend() - i, nums[n - 1 - i]) - right.rbegin();
    }
    int result = n;
    for (int i = 1; i < n - 1; ++i)
        result = min(result, n - (left[i] + 1) - (right[i] + 1));

    return result;
}
```


```python
def maximum_generated(n: int) -> int:
    if n == 0:
        return 0
    nums = [0] * (n + 1)
    nums[1] = 1
    for i in range(2, n + 1):
        nums[i] = nums[i // 2] if i % 2 == 0 else nums[i // 2] + nums[i // 2 + 1]
    return max(nums)
```

```cpp
#include <vector>
using namespace std;

int maximumGenerated(int n) {
    if (n == 0) {
        return 0;
    }
    vector<int> nums(n + 1);
    nums[1] = 1;
    for (int i = 2; i <= n; ++i) {
        nums[i] = i % 2 == 0 ? nums[i / 2] : nums[i / 2] + nums[i / 2 + 1];
    }
    return *max_element(nums.begin(), nums.end());
}
```


```java
import java.util.Arrays;

public int closestCost(int[] baseCosts, int[] toppingCosts, int target) {
    int closest = Integer.MAX_VALUE;
    Arrays.sort(toppingCosts);

    for (int base : baseCosts) {
        int diff = Math.abs(target - base);
        if (diff < closest) {
            closest = diff;
        }
        if (diff == 0) {
            return target;
        }
        for (int t0 = 0; t0 <= 2; t0++) {
            int x1 = base + t0 * toppingCosts[0];
            int diff1 = Math.abs(target - x1);
            if (diff1 < closest) {
                closest = diff1;
            }
            if (diff1 == 0) {
                return target;
            }
            for (int t1 = 0; t1 <= 2; t1++) {
                int x2 = x1 + t1 * toppingCosts[1];
                int diff2 = Math.abs(target - x2);
                if (diff2 < closest) {
                    closest = diff2;
                }
                if (diff2 == 0) {
                    return target;
                }
            }
        }
    }
    return target - closest;
}
```

baseCosts = \[1,7\], toppingCosts = \[3,4\], target = 10

```python
from itertools import product

def closest_cost(base_costs, topping_costs, target):
    closest = float('inf')
    topping_combinations = list(product([0, 1, 2], repeat=len(topping_costs)))

    for base in base_costs:
        for combination in topping_combinations:
            combination_cost = sum(x * y for x, y in zip(topping_costs, combination))
            diff = abs(target - (base + combination_cost))
            if diff < closest:
                closest = diff
            if diff == 0:
                return target

    return target - closest
```


```cpp
int nearestValidPoint(int x, int y, vector<vector<int>>& points) {
    int min_distance = INT_MAX, index = -1;
    for (int i = 0; i < points.size(); i++) {
        if (x == points[i][0] || y == points[i][1]) {
            int distance = abs(x - points[i][0]) + abs(y - points[i][1]);
            if (distance < min_distance) {
                min_distance = distance;
                index = i;
            }
        }
    }
    return index;
}
```

```java
public int nearestValidPoint(int x, int y, int[][] points) {
    int min_distance = Integer.MAX_VALUE, index = -1;
    for (int i = 0; i < points.length; i++) {
        if (x == points[i][0] || y == points[i][1]) {
            int distance = Math.abs(x - points[i][0]) + Math.abs(y - points[i][1]);
            if (distance < min_distance) {
                min_distance = distance;
                index = i;
            }
        }
    }
    return index;
}
```


```python
def maximum_wealth(accounts):
    return max(sum(customer) for customer in accounts)
```

```java
public int maximumWealth(int[][] accounts) {
    int maxWealth = 0;
    for (int[] customer : accounts) {
        int wealth = 0;
        for (int account : customer) {
            wealth += account;
        }
        maxWealth = Math.max(maxWealth, wealth);
    }
    return maxWealth;
}
```


```cpp
#include <vector>
#include <stack>

std::vector<int> mostCompetitive(std::vector<int>& nums, int k) {
    std::stack<int> stk;
    int n = nums.size();

    for (int i = 0; i < n; i++) {
        while (!stk.empty() && nums[i] < stk.top() && stk.size() + n - i > k) {
            stk.pop();
        }
        if (stk.size() < k) {
            stk.push(nums[i]);
        }
    }

    std::vector<int> result(k);
    for (int i = k - 1; i >= 0; i--) {
        result[i] = stk.top();
        stk.pop();
    }

    return result;
}
```

```python
def most_competitive(nums, k):
    stack = []
    n = len(nums)

    for i in range(n):
        while stack and nums[i] < stack[-1] and len(stack) + n - i > k:
            stack.pop()
        if len(stack) < k:
            stack.append(nums[i])

    return stack
```


```java
public int numberOfMatches(int n) {
    return n - 1;
}
```

```cpp
int numberOfMatches(int n) {
    return n - 1;
}
```


```python
def maximum_unique_subarray(nums):
    max_sum, current_sum, left = 0, 0, 0
    elements = set()

    for right in range(len(nums)):
        while nums[right] in elements:
            elements.remove(nums[left])
            current_sum -= nums[left]
            left += 1

        elements.add(nums[right])
        current_sum += nums[right]
        max_sum = max(max_sum, current_sum)

    return max_sum
```

sentence1 =  "My name is Haley ", sentence2 =  "My Haley "

The quick brown fox jumps over the lazy dog
,

I have a dream that one day this nation will rise up
,

Algorithm Programmer
Programmer Algorithm

Experience
Experience is the best teacher

```cpp
#include <unordered_set>
#include <vector>

int maximumUniqueSubarray(std::vector<int>& nums) {
    int max_sum = 0, current_sum = 0, left = 0;
    std::unordered_set<int> elements;

    for (int right = 0; right < nums.size(); ++right) {
        while (elements.count(nums[right])) {
            elements.erase(nums[left]);
            current_sum -= nums[left++];
        }

        elements.insert(nums[right]);
        current_sum += nums[right];
        max_sum = std::max(max_sum, current_sum);
    }

    return max_sum;
}
```


```python
from collections import deque

def maxResult(nums, k):
    n = len(nums)
    dq = deque()
    dp = [0] * n

    dp[0] = nums[0]
    dq.append(0)

    for i in range(1, n):
        while dq and dq[0] < i - k:
            dq.popleft()

        dp[i] = nums[i] + dp[dq[0]]

        while dq and dp[i] >= dp[dq[-1]]:
            dq.pop()

        dq.append(i)

    return dp[-1]
```

```cpp
int maxResult(vector<int>& nums, int k) {
    int n = nums.size();
    deque<int> dq;
    vector<int> dp(n);

    dp[0] = nums[0];
    dq.push_back(0);

    for (int i = 1; i < n; ++i) {
        while (!dq.empty() && dq.front() < i - k) {
            dq.pop_front();
        }

        dp[i] = nums[i] + dp[dq.front()];

        while (!dq.empty() && dp[i] >= dp[dq.back()]) {
            dq.pop_back();
        }

        dq.push_back(i);
    }

    return dp.back();
}
```


```python
def count_trees(pairs):
    nodes = len(pairs) + 1
    in_degrees = [0] * nodes
    for x, y in pairs:
        in_degrees[y] += 1

    res = 1
    for in_degree in in_degrees[1:]:
        res *= in_degree

    return res
```

```cpp
#include <vector>
using namespace std;

int countTrees(vector<vector<int>>& pairs) {
    int nodes = pairs.size() + 1;
    vector<int> in_degrees(nodes, 0);
    for (vector<int>& pair : pairs) {
        in_degrees[pair[1]]++;
    }

    int res = 1;
    for (int i = 1; i < nodes; i++) {
        res *= in_degrees[i];
    }

    return res;
}
```


```java
public int signFunc(int x) {
    if(x > 0) return 1;
    if(x < 0) return -1;
    return 0;
}

public int arraySign(int[] nums) {
    int product = 1;
    for(int i = 0; i < nums.length; i++) {
        product *= signFunc(nums[i]);
    }
    return product;
}
```

```python
def signFunc(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

def arraySign(nums):
    product = 1
    for num in nums:
        product *= signFunc(num)
    return product
```


```python
def maximizeXor(nums, queries):
    trie = {}
    nums.sort()

    new_queries = sorted([(x, m, i) for i, (x, m) in enumerate(queries)], key=lambda x: x[1])

    ans = [0] * len(queries)

    idx = 0
    for x, m, i in new_queries:
        while idx < len(nums) and nums[idx] <= m:
            t = nums[idx]
            idx += 1
            cur = trie
            for j in range(31, -1, -1):
                bit = (t >> j) & 1
                cur = cur.setdefault(bit, {})
        cur = trie
        xor_value = 0
        for j in range(31, -1, -1):
            bit = (x >> j) & 1
            if 1 ^ bit in cur:
                cur = cur[1 ^ bit]
                xor_value |= 1 << j
            else:
                cur = cur[bit]
        ans[i] = xor_value if cur else -1

    return ans
```

```cpp
#include <vector>
#include <algorithm>
using namespace std;

vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) {
    sort(nums.begin(), nums.end());
    for (int i = 0; i < queries.size(); ++i) {
        queries[i].push_back(i);
    }
    sort(queries.begin(), queries.end(), [](vector<int> &a, vector<int> &b) {
        return a[1] < b[1];
    });

    vector<int> ans(queries.size());
    int idx = 0, trie[200010][2] = {}, sum[200010] = {1}, cnt = 0;
    for (const auto &q : queries) {
        int x = q[0], m = q[1], k = q[2], p = 0;
        while (idx < nums.size() && nums[idx] <= m) {
            int cur = 0, t = nums[idx++];
            for (int i = 31; i >= 0; --i) {
                int bit = ((t >> i) & 1);
                if (!trie[cur][bit]) {
                    trie[cur][bit] = ++cnt;
                }
                cur = trie[cur][bit];
            }
            sum[cur]++;
        }
        if (!cnt) {
            ans[k] = -1;
            continue;
        }
        int cur = 0, ans2 = 0;
        for (int i = 31; i >= 0; --i) {
            int bit = ((x >> i) & 1);
            if (trie[cur][bit ^ 1]) {
                cur = trie[cur][bit ^ 1];
                ans2 |= (1 << i);
            } else {
                cur = trie[cur][bit];
            }
        }
        ans[k] = ans2;
    }
    return ans;
}
```


```java
public int minOperations(int[] nums) {
    int operations = 0;
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] <= nums[i - 1]) {
            operations += (nums[i - 1] - nums[i]) + 1;
            nums[i] = nums[i - 1] + 1;
        }
    }
    return operations;
}
```

```python
def min_operations(nums):
    operations = 0
    for i in range(1, len(nums)):
        if nums[i] <= nums[i - 1]:
            operations += (nums[i - 1] - nums[i]) + 1
            nums[i] = nums[i - 1] + 1
    return operations
```


```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public int[] countPoints(int[][] points, int[][] queries) {
    int[] answer = new int[queries.length];
    for (int i = 0; i < queries.length; i++) {
        int inside = 0;
        for (int[] point : points) {
            int dx = point[0] - queries[i][0];
            int dy = point[1] - queries[i][1];
            if (dx * dx + dy * dy <= queries[i][2] * queries[i][2]) {
                inside++;
            }
        }
        answer[i] = inside;
    }
    return answer;
}
```

```python
def countPoints(points, queries):
    answer = []
    for query in queries:
        inside = 0
        for point in points:
            dx = point[0] - query[0]
            dy = point[1] - query[1]
            if dx * dx + dy * dy <= query[2] * query[2]:
                inside += 1
        answer.append(inside)
    return answer
```


```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

public class Solution {
    static final int MOD = 1000000007;

    public static ArrayList<Integer> productWays(int[][] queries) {
        ArrayList<Integer> res = new ArrayList<>();
        for (int[] q : queries) {
            int n = q[0], k = q[1];

            List<Integer> pf = new ArrayList<>();
            Map<Integer, Integer> pm = new HashMap<>();
            for (int i = 2; i * i <= k; ++i) {
                int cnt = 0;
                while (k % i == 0) {
                    cnt++;
                    k /= i;
                }
                if (cnt != 0) {
                    pf.add(cnt);
                    pm.put(cnt, pm.getOrDefault(cnt, 0) + 1);
                }
            }

            if (k > 1) {
                pm.put(k, pm.getOrDefault(k, 0) + 1);
                pf.add(1);
            }

            long ans = 1;
            for (int p : pf) {
                ans = (ans * (p * (n - 1) + 1)) % MOD;
            }

            res.add((int) ans);
        }
        return res;
    }
}
```

```cpp
#include <vector>
#include <map>
#include <cmath>

using namespace std;

const int MOD = 1e9 + 7;

vector<int> productWays(vector<vector<int>>& queries) {
    vector<int> res;
    for (auto& q : queries) {
        int n = q[0], k = q[1];

        vector<int> pf;
        map<int, int> pm;
        for (int i = 2; i * i <= k; ++i) {
            int cnt = 0;
            while (k % i == 0) {
                cnt++;
                k /= i;
            }
            if (cnt) {
                pf.push_back(cnt);
                pm[cnt]++;
            }
        }

        if (k > 1) {
            pm[k]++;
            pf.push_back(1);
        }

        long long ans = 1;
        for (int p : pf) {
            ans = (ans * (p * (n - 1) + 1)) % MOD;
        }

        res.push_back(ans);
    }
    return res;
}
```


```python
def maxFrequency(nums: List[int], k: int) -> int:
    nums.sort()
    n, i, s, max_freq = len(nums), 0, 0, 0

    for j in range(n):
        s += nums[j]
        while s + k < nums[j] * (j - i + 1):
            s -= nums[i]
            i += 1
        max_freq = max(max_freq, j - i + 1)

    return max_freq
```

```cpp
int maxFrequency(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    int n = nums.size(), i = 0;
    long long sum = 0;
    int max_freq = 0;

    for (int j = 0; j < n; j++) {
        sum += nums[j];
        while (sum + k < static_cast<long long>(nums[j]) * (j - i + 1)) {
            sum -= nums[i++];
        }
        max_freq = max(max_freq, j - i + 1);
    }

    return max_freq;
}
```


```python
def decode(encoded, first):
    arr = [first]
    for num in encoded:
        arr.append(arr[-1] ^ num)
    return arr
```

word =  "aeiaaioaaaaeiiiiouuuooaauuaeiu "

abcde aeeeeiiiioouuuaaeiou uuuuiiiiooaeea aeiaaioaaaaeiiiiouuuooaauuaeiu ioueoa aeiaaioaaaaeiiiiouuuooaauuaeiu ou aaaaa aei aeiaaioaaaaeiiiiouuuooaauuaeiu

```cpp
#include <vector>

std::vector<int> decode(std::vector<int>& encoded, int first) {
    std::vector<int> arr(encoded.size() + 1);
    arr[0] = first;
    for (int i = 0; i < encoded.size(); i++) {
        arr[i + 1] = arr[i] ^ encoded[i];
    }
    return arr;
}
```


```cpp
#include <algorithm>
#include <string>
using namespace std;

string nextPalindrome(string num) {
    int n = num.size();
    string firstHalf = num.substr(0, (n + 1) / 2);
    next_permutation(firstHalf.begin(), firstHalf.end());

    if (firstHalf > num.substr(0, (n + 1) / 2)) {
        string secondHalf = firstHalf;
        reverse(secondHalf.begin(), secondHalf.end());
        if (n % 2 == 1) secondHalf = secondHalf.substr(1);
        return firstHalf + secondHalf;
    }

    return "";
}
```

```java
import java.util.Arrays;

public class Solution {
    public String nextPalindrome(String num) {
        int n = num.length();
        char[] firstHalf = num.substring(0, (n + 1) / 2).toCharArray();
        if (!nextPermutation(firstHalf)) return "";

        String secondHalf = new StringBuilder(String.valueOf(firstHalf)).reverse().toString();
        if (n % 2 == 1) secondHalf = secondHalf.substring(1);
        return String.valueOf(firstHalf) + secondHalf;
    }

    private boolean nextPermutation(char[] array) {
        int n = array.length;
        int k = n - 2;
        while (k >= 0 && array[k] >= array[k + 1]) k--;

        if (k == -1) return false;

        int l = n - 1;
        while (array[l] <= array[k]) l--;

        char temp = array[k];
        array[k] = array[l];
        array[l] = temp;

        int left = k + 1, right = n - 1;
        while (left < right) {
            temp = array[left];
            array[left++] = array[right];
            array[right--] = temp;
        }

        return true;
    }
}
```


```java
public int maximumElementAfterDecrementingAndRearranging(int[] arr) {
    Arrays.sort(arr);
    arr[0] = 1;
    for (int i = 1; i < arr.length; i++) {
        arr[i] = Math.min(arr[i], arr[i - 1] + 1);
    }
    return arr[arr.length - 1];
}
```

```cpp
int maximumElementAfterDecrementingAndRearranging(vector<int>& arr) {
    sort(arr.begin(), arr.end());
    arr[0] = 1;
    for (int i = 1; i < arr.size(); i++) {
        arr[i] = min(arr[i], arr[i - 1] + 1);
    }
    return arr[arr.size() - 1];
}
```


```cpp
#include <unordered_map>
#include <vector>
using namespace std;

vector<int> distinctNumbersInSubarrays(vector<int>& nums, int k) {
    unordered_map<int, int> counts;
    vector<int> ans;
    for (int i = 0; i < nums.size(); i++) {
        counts[nums[i]]++;
        if (i >= k) {
            counts[nums[i - k]]--;
            if (counts[nums[i - k]] == 0) {
                counts.erase(nums[i - k]);
            }
        }
        if (i >= k - 1) {
            ans.push_back(counts.size());
        }
    }
    return ans;
}
```

```python
def distinct_numbers_in_subarrays(nums, k):
    counts = {}
    ans = []
    for i, num in enumerate(nums):
        counts[num] = counts.get(num, 0) + 1
        if i >= k:
            counts[nums[i - k]] -= 1
            if counts[nums[i - k]] == 0:
                del counts[nums[i - k]]
        if i >= k - 1:
            ans.append(len(counts))
    return ans
```


```cpp
int maxAliveYear(vector<vector<int>>& logs) {
    vector<int> years(101, 0);
    for (vector<int> log : logs) {
        years[log[0] - 1950]++;
        years[log[1] - 1950]--;
    }
    int max_population = years[0];
    int max_year = 1950;
    for (int i = 1; i < 101; i++) {
        years[i] += years[i - 1];
        if (years[i] > max_population) {
            max_population = years[i];
            max_year = i + 1950;
        }
    }
    return max_year;
}
```

```java
public int maxAliveYear(int[][] logs) {
    int[] years = new int[101];
    for (int[] log : logs) {
        years[log[0] - 1950]++;
        years[log[1] - 1950]--;
    }
    int max_population = years[0];
    int max_year = 1950;
    for (int i = 1; i < 101; i++) {
        years[i] += years[i - 1];
        if (years[i] > max_population) {
            max_population = years[i];
            max_year = i + 1950;
        }
    }
    return max_year;
}
```


```java
public int maxDistance(int[] nums1, int[] nums2) {
    int i = 0, j = 0, maxDist = 0;
    while (i < nums1.length && j < nums2.length) {
        if (nums1[i] > nums2[j]) {
            ++i;
        } else {
            maxDist = Math.max(maxDist, j - i);
            ++j;
        }
    }
    return maxDist;
}
```

```python
def maxDistance(nums1, nums2):
    i, j, maxDist = 0, 0, 0
    while i < len(nums1) and j < len(nums2):
        if nums1[i] > nums2[j]:
            i += 1
        else:
            maxDist = max(maxDist, j - i)
            j += 1
    return maxDist
```


```java
import java.util.PriorityQueue;

public int kthLargestValue(int[][] matrix, int k) {
    int m = matrix.length;
    int n = matrix[0].length;
    int[][] prefixXOR = new int[m + 1][n + 1];
    PriorityQueue<Integer> pq = new PriorityQueue<>(k);

    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            prefixXOR[i][j] = matrix[i - 1][j - 1] ^ prefixXOR[i - 1][j] ^ prefixXOR[i][j - 1] ^ prefixXOR[i - 1][j - 1];
            pq.offer(prefixXOR[i][j]);
            if (pq.size() > k) {
                pq.poll();
            }
        }
    }
    return pq.peek();
}
```

```cpp
#include <vector>
#include <queue>

int kthLargestValue(std::vector<std::vector<int>>& matrix, int k) {
    int m = matrix.size(), n = matrix[0].size();
    std::vector<std::vector<int>> prefixXOR(m + 1, std::vector<int>(n + 1, 0));
    std::priority_queue<int, std::vector<int>, std::greater<int>> pq;

    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            prefixXOR[i][j] = matrix[i - 1][j - 1] ^ prefixXOR[i - 1][j] ^ prefixXOR[i][j - 1] ^ prefixXOR[i - 1][j - 1];
            pq.push(prefixXOR[i][j]);
            if (pq.size() > k) {
                pq.pop();
            }
        }
    }
    return pq.top();
}
```


```python
def subsetXORSum(nums):
    ans = 0
    n = len(nums)
    max_val = 1 << n
    for i in range(1, max_val):
        xor_total = 0
        for j in range(n):
            if i & (1 << j):
                xor_total ^= nums[j]
        ans += xor_total
    return ans
```

```java
public int subsetXORSum(int[] nums) {
    int ans = 0, n = nums.length, max_val = 1 << n;
    for (int i = 1; i < max_val; i++) {
        int xor_total = 0;
        for (int j = 0; j < n; j++) {
            if ((i & (1 << j)) > 0) {
                xor_total ^= nums[j];
            }
        }
        ans += xor_total;
    }
    return ans;
}
```


```java
public int minSwaps(String s) {
    int zeroCount = 0, oneCount = 0;
    for (char c : s.toCharArray()) {
        if (c == '0') {
            zeroCount++;
        } else {
            oneCount++;
        }
    }

    if (Math.abs(zeroCount - oneCount) > 1) {
        return -1;
    }

    int swaps1 = 0, swaps2 = 0;
    for (int i = 0; i < s.length(); i++) {
        if (i % 2 == 0 && s.charAt(i) != '0') {
            swaps1++;
        }
        if (i % 2 == 1 && s.charAt(i) != '1') {
            swaps1++;
        }
    }
    swaps1 = swaps1 / 2;

    for (int i = 0; i < s.length(); i++) {
        if (i % 2 == 0 && s.charAt(i) != '1') {
            swaps2++;
        }
        if (i % 2 == 1 && s.charAt(i) != '0') {
            swaps2++;
        }
    }
    swaps2 = swaps2 / 2;

    if (zeroCount == oneCount) {
        return Math.min(swaps1, swaps2);
    }
    return (zeroCount > oneCount) ? swaps2 : swaps1;
}
```

```python
def minSwaps(s):
    zeroCount = s.count('0')
    oneCount = len(s) - zeroCount

    if abs(zeroCount - oneCount) > 1:
        return -1

    swaps1 = swaps2 = 0
    for i, c in enumerate(s):
        if i % 2 == 0 and c != '0':
            swaps1 += 1
        if i % 2 == 1 and c != '1':
            swaps1 += 1
    swaps1 = swaps1 // 2

    for i, c in enumerate(s):
        if i % 2 == 0 and c != '1':
            swaps2 += 1
        if i % 2 == 1 and c != '0':
            swaps2 += 1
    swaps2 = swaps2 // 2

    if zeroCount == oneCount:
        return min(swaps1, swaps2)
    return swaps2 if zeroCount > oneCount else swaps1
```


```java
public boolean checkZeroOnes(String s) {
    int max_ones = 0, max_zeros = 0, current_ones = 0, current_zeros = 0;
    for (char c : s.toCharArray()) {
        if (c == '1') {
            current_ones++;
            current_zeros = 0;
        } else {
            current_zeros++;
            current_ones = 0;
        }
        max_ones = Math.max(max_ones, current_ones);
        max_zeros = Math.max(max_zeros, current_zeros);
    }
    return max_ones > max_zeros;
}
```

False True True False True True False False False

```python
def checkZeroOnes(s: str) -> bool:
    max_ones, max_zeros, current_ones, current_zeros = 0, 0, 0, 0
    for c in s:
        if c == '1':
            current_ones += 1
            current_zeros = 0
        else:
            current_zeros += 1
            current_ones = 0
        max_ones = max(max_ones, current_ones)
        max_zeros = max(max_zeros, current_zeros)
    return max_ones > max_zeros
```


```java
import java.util.*;

public int[][] highestIsland(int[][] isWater) {
    int m = isWater.length;
    int n = isWater[0].length;
    int[][] height = new int[m][n];
    Queue<int[]> q = new LinkedList<>();

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (isWater[i][j] == 1) {
                height[i][j] = 0;
                q.offer(new int[]{i, j});
            } else {
                height[i][j] = -1;
            }
        }
    }

    int[] dx = {-1, 0, 1, 0};
    int[] dy = {0, 1, 0, -1};

    while (!q.isEmpty()) {
        int[] curr = q.poll();
        int x = curr[0];
        int y = curr[1];

        for (int i = 0; i < 4; i++) {
            int newX = x + dx[i];
            int newY = y + dy[i];

            if (newX >= 0 && newX < m && newY >= 0 && newY < n && height[newX][newY] == -1) {
                height[newX][newY] = height[x][y] + 1;
                q.offer(new int[]{newX, newY});
            }
        }
    }

    return height;
}
```

aababaab xyzzaz aabababababababaab aabababababaa xyxyxxyxxxyxy aabababababababaa aabababababaab aba aabababaa aababcabc xyxyxyxyx xyxyxyxyxy aababab xyxyxxxyxxy xyz xyxyxyx xyxyxxyxxyx abc xyxyxy aabababab xyxyz xyxyxyxy xyxyxxyxxxyx aaaaaa xyxyxxxyxxyxxyxy xyxyxxxyx aababaa aabababaab xyxyxxxyxy xyzzaz aababababaab xyxyxxyxy xyxyxxxyxxyxxyx aababababababaa aabbaabb aaabbb xyxyxxyx aababababababab xyxyxxxyxxxyxxxy aabbaabbaabb aabbaab abcabc xyxyxxy aabababababab xyxyxxyxxyxy xyxyx aabbcc xyxyxxyxxxyxxxy xyxyxxxyxxxy aabababababababab xyzzaz aabaaab aababababaa aababababab

```python
from collections import deque

def highest_island(is_water):
    m, n = len(is_water), len(is_water[0])
    height = [[-1] * n for _ in range(m)]
    q = deque()

    for i in range(m):
        for j in range(n):
            if is_water[i][j] == 1:
                height[i][j] = 0
                q.append((i, j))

    dx = [-1, 0, 1, 0]
    dy = [0, 1, 0, -1]

    while q:
        x, y = q.popleft()

        for i in range(4):
            newX = x + dx[i]
            newY = y + dy[i]

            if 0 <= newX < m and 0 <= newY < n and height[newX][newY] == -1:
                height[newX][newY] = height[x][y] + 1
                q.append((newX, newY))

    return height
```


```cpp
int minPairSum(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int max_sum = 0;
    for (int i = 0; i < nums.size() / 2; ++i)
        max_sum = max(max_sum, nums[i] + nums[nums.size() - 1 - i]);
    return max_sum;
}
```

```python
def minPairSum(nums):
    nums.sort()
    max_sum = 0
    for i in range(len(nums) // 2):
        max_sum = max(max_sum, nums[i] + nums[-1 - i])
    return max_sum
```


```java
public int minSkips(int[] dist, int speed, int hoursBefore) {
    int n = dist.length;
    double[][] dp = new double[n + 1][n + 1];

    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            dp[i][j] = 1e9;
        }
    }
    dp[0][0] = 0;

    for (int i = 0; i < n; i++) {
        for (int j = -1; j < i; j++) {
            double t = dist[i] / (double)speed + (j != -1 ? 1 : 0);
            dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i][j] + t);
            double skipped_t = Math.ceil(dp[i][j] + dist[i] / (double)speed) - dp[i][j];
            dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + skipped_t);
        }
    }

    for (int i = 0; i <= n; i++) {
        if (dp[n][i] <= hoursBefore) {
            return i;
        }
    }
    return -1;
}
```

dist = \[1,3,2\], speed = 4, hoursBefore = 2

```cpp
#include <vector>
#include <limits>
using namespace std;

int minSkips(vector<int>& dist, int speed, int hoursBefore) {
    int n = dist.size();
    vector<vector<double>> dp(n + 1, vector<double>(n + 1, 1e9));
    dp[0][0] = 0;

    for (int i = 0; i < n; ++i) {
        for (int j = -1; j < i; ++j) {
            double t = dist[i] / double(speed) + (j != -1);
            dp[i + 1][j + 1] = min(dp[i + 1][j + 1], dp[i][j] + t);
            double skipped_t = ceil(dp[i][j] + dist[i] / double(speed)) - dp[i][j];
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j] + skipped_t);
        }
    }

    for (int i = 0; i <= n; ++i) {
        if (dp[n][i] <= hoursBefore) return i;
    }
    return -1;
}
```


```java
import java.util.*;

class Solution {
    public int minTrioDegree(int n, int[][] edges) {
        Map<Integer, Map<Integer, Boolean>> graph = new HashMap<>();
        int[] degree = new int[n + 1];

        for (int[] edge : edges) {
            graph.computeIfAbsent(edge[0], k -> new HashMap<>()).put(edge[1], true);
            graph.computeIfAbsent(edge[1], k -> new HashMap<>()).put(edge[0], true);
            degree[edge[0]]++;
            degree[edge[1]]++;
        }

        int minDegree = Integer.MAX_VALUE;
        for (int[] edge : edges) {
            int u = edge[0], v = edge[1];
            for (int w = 1; w <= n; ++w) {
                if (graph.get(u).get(w) != null && graph.get(v).get(w) != null) {
                    minDegree = Math.min(minDegree, degree[u] + degree[v] + degree[w] - 6);
                }
            }
        }

        return minDegree == Integer.MAX_VALUE ? -1 : minDegree;
    }
}
```

```cpp
#include <vector>
#include <unordered_map>
#include <algorithm>

int minTrioDegree(int n, std::vector<std::vector<int>>& edges) {
    std::unordered_map<int, std::unordered_map<int, bool>> graph;
    std::vector<int> degree(n + 1, 0);

    for (auto& edge : edges) {
        graph[edge[0]][edge[1]] = graph[edge[1]][edge[0]] = true;
        degree[edge[0]]++;
        degree[edge[1]]++;
    }

    int minDegree = INT_MAX;
    for (auto& edge : edges) {
        int u = edge[0], v = edge[1];
        for (int w = 1; w <= n; ++w) {
            if (graph[u][w] && graph[v][w]) {
                minDegree = std::min(minDegree, degree[u] + degree[v] + degree[w] - 6);
            }
        }
    }

    return minDegree == INT_MAX ? -1 : minDegree;
}
```


```java
public boolean isCovered(int[][] ranges, int left, int right) {
    for (int i = left; i <= right; i++) {
        boolean found = false;
        for (int[] range : ranges) {
            if (i >= range[0] && i <= range[1]) {
                found = true;
                break;
            }
        }
        if (!found) return false;
    }
    return true;
}
```

True False False False True False False False True False True False False False True False False False True True False True True True True False False False True False True False False True False True True True True True True False True False False False False False True

```python
def isCovered(ranges: List[List[int]], left: int, right: int) -> bool:
    for i in range(left, right + 1):
        found = False
        for _range in ranges:
            if _range[0] <= i <= _range[1]:
                found = True
                break
        if not found:
            return False
    return True
```


```cpp
#include <vector>
#include <string>

std::vector<int> minOperations(std::string boxes) {
    std::vector<int> result(boxes.size(), 0);
    int count = 0, total = 0;

    for (int i = 0; i < boxes.size(); i++) {
        total += count;
        result[i] = total;
        if (boxes[i] == '1') count++;
    }

    count = 0;
    total = 0;
    for (int i = boxes.size() - 1; i >= 0; i--) {
        total += count;
        result[i] += total;
        if (boxes[i] == '1') count++;
    }

    return result;
}
```

```python
def min_operations(boxes: str):
    result = [0] * len(boxes)
    count, total = 0, 0

    for i in range(len(boxes)):
        total += count
        result[i] = total
        if boxes[i] == '1':
            count += 1

    count, total = 0, 0
    for i in range(len(boxes) - 1, -1, -1):
        total += count
        result[i] += total
        if boxes[i] == '1':
            count += 1

    return result
```


```java
public int maximumScore(int[] nums, int[] multipliers) {
    int n = nums.length, m = multipliers.length;
    int[][] dp = new int[m + 1][m + 1];
    int maxScore = Integer.MIN_VALUE;

    for (int i = 0; i <= m; i++) {
        for (int j = 0; i + j <= m; j++) {
            if (i == 0 && j == 0) continue;
            int score = 0;
            if (i == 0) {
                score = dp[i][j - 1] + nums[n - j] * multipliers[i + j - 1];
            } else if (j == 0) {
                score = dp[i - 1][j] + nums[i - 1] * multipliers[i + j - 1];
            } else {
                score = Math.max(dp[i - 1][j] + nums[i - 1] * multipliers[i + j - 1],
                                dp[i][j - 1] + nums[n - j] * multipliers[i + j - 1]);
            }
            dp[i][j] = score;
            if (i + j == m) {
                maxScore = Math.max(maxScore, score);
            }
        }
    }

    return maxScore;
}
```

```cpp
#include <vector>
#include <algorithm>
using namespace std;

int maximumScore(vector<int>& nums, vector<int>& multipliers) {
    int n = nums.size(), m = multipliers.size();
    vector<vector<int>> dp(m + 1, vector<int>(m + 1, 0));
    int maxScore = INT_MIN;

    for (int i = 0; i <= m; ++i) {
        for (int j = 0; i + j <= m; ++j) {
            if (i == 0 && j == 0) continue;
            int score = 0;
            if (i == 0) {
                score = dp[i][j - 1] + nums[n - j] * multipliers[i + j - 1];
            } else if (j == 0) {
                score = dp[i - 1][j] + nums[i - 1] * multipliers[i + j - 1];
            } else {
              score = max(dp[i - 1][j] + nums[i - 1] * multipliers[i + j - 1],
                          dp[i][j - 1] + nums[n - j] * multipliers[i + j - 1]);
            }
            dp[i][j] = score;
            if (i + j == m) {
                maxScore = max(maxScore, score);
            }
        }
    }

    return maxScore;
}
```


```cpp
int maximumRemovals(string s, string p, vector<int>& removable) {
    int low = 0, high = removable.size();
    while (low < high) {
        int mid = (low + high + 1) / 2;
        string temp_s = s;
        for (int i = 0; i < mid; i++) {
            temp_s[removable[i]] = '-';
        }
        int i = 0, j = 0;
        while (i < temp_s.size() && j < p.size()) {
            if (temp_s[i] == p[j]) {
                j++;
            }
            i++;
        }
        if (j == p.size()) {
            low = mid;
        } else {
            high = mid - 1;
        }
    }
    return low;
}
```

s =  "abcacb ", p =  "ab ", removable = \[3,1,0\]

```python
def maximumRemovals(s: str, p: str, removable: List[int]) -> int:
    low, high = 0, len(removable)
    while low < high:
        mid = (low + high + 1) // 2
        temp_s = list(s)
        for i in range(mid):
            temp_s[removable[i]] = '-'
        i, j = 0, 0
        while i < len(temp_s) and j < len(p):
            if temp_s[i] == p[j]:
                j += 1
            i += 1
        if j == len(p):
            low = mid
        else:
            high = mid - 1
    return low
```


```java
public boolean aliceWins(int[] piles) {
    int xorSum = 0;
    for (int pile : piles) {
        xorSum ^= pile;
    }
    return xorSum != 0;
}
```

true true true true true true true true true false true true true true false true true true true false true true true true true true true true false true true true true true true true false true true true true true false true true true true true true true true true true true true true true true true true true true true false true true

```cpp
bool aliceWins(vector<int>& piles) {
    int xor_sum = 0;
    for (int pile : piles) {
        xor_sum ^= pile;
    }
    return xor_sum != 0;
}
```


```python
def canBeIncreasing(nums):
    count = 0
    for i in range(1, len(nums)):
        if nums[i - 1] >= nums[i]:
            count += 1
            if count > 1: return False
            if i > 1 and nums[i - 2] >= nums[i] and i < len(nums) - 1 and nums[i - 1] >= nums[i + 1]: return False
    return True
```

true true false true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true true

```cpp
bool canBeIncreasing(vector<int>& nums) {
    int count = 0;
    for (int i = 1; i < nums.size(); ++i) {
        if (nums[i - 1] >= nums[i]) {
            count++;
            if (count > 1) return false;
            if (i > 1 && nums[i - 2] >= nums[i] && i < nums.size() - 1 && nums[i - 1] >= nums[i + 1]) return false;
        }
    }
    return true;
}
```


```java
public int maxScore(int[] nums, int k) {
    int n = nums.length;
    int result = 0;
    for (int i = k; i >= 0; i--) {
        for (int j = k; j < n; j++) {
            int minVal = nums[i];
            for (int x = i; x <= j; x++)
                minVal = Math.min(minVal, nums[x]);
            result = Math.max(result, minVal * (j - i + 1));
        }
    }
    return result;
}
```

```python
def maxScore(nums: List[int], k: int) -> int:
    n = len(nums)
    result = 0
    for i in range(k, -1, -1):
        for j in range(k, n):
            min_val = min(nums[i:j+1])
            result = max(result, min_val * (j - i + 1))
    return result
```


```cpp
int eliminateMaximum(vector<int>& dist, vector<int>& speed) {
    int n = dist.size();
    vector<int> time_to_reach_city(n);
    for (int i = 0; i < n; i++) {
        time_to_reach_city[i] = (dist[i] + speed[i] - 1) / speed[i];
    }
    sort(time_to_reach_city.begin(), time_to_reach_city.end());
    int eliminated = 0;
    for (int i = 0; i < n && time_to_reach_city[i] > i; i++) {
        eliminated++;
    }
    return eliminated;
}
```

```java
public int eliminateMaximum(int[] dist, int[] speed) {
    int n = dist.length;
    int[] timeToReachCity = new int[n];
    for (int i = 0; i < n; i++) {
        timeToReachCity[i] = (dist[i] + speed[i] - 1) / speed[i];
    }
    Arrays.sort(timeToReachCity);
    int eliminated = 0;
    for (int i = 0; i < n && timeToReachCity[i] > i; i++) {
        eliminated++;
    }
    return eliminated;
}
```


```java
public long goodDigitStrings(int n) {
    final int mod = 1000000007;
    long evenCount = 1, primeCount = 1;
    for (int i = 0; i < n; ++i) {
        if (i % 2 == 0) evenCount = (evenCount * 5) % mod;
        else primeCount = (primeCount * 4) % mod;
    }
    return (evenCount * primeCount) % mod;
}
```

```python
def goodDigitStrings(n: int) -> int:
    MOD = 1000000007
    even_count, prime_count = 1, 1
    for i in range(n):
        if i % 2 == 0:
            even_count = (even_count * 5) % MOD
        else:
            prime_count = (prime_count * 4) % MOD
    return (even_count * prime_count) % MOD
```


```java
public int maxAscendingSum(int[] nums) {
    int maxSum = 0, currentSum = nums[0];

    for (int i = 1; i < nums.length; ++i) {
        if (nums[i] > nums[i - 1]) {
            currentSum += nums[i];
        } else {
            maxSum = Math.max(maxSum, currentSum);
            currentSum = nums[i];
        }
    }

    return Math.max(maxSum, currentSum);
}
```

```cpp
int maxAscendingSum(vector<int>& nums) {
    int maxSum = 0, currentSum = nums[0];

    for (int i = 1; i < nums.size(); ++i) {
        if (nums[i] > nums[i - 1]) {
            currentSum += nums[i];
        } else {
            maxSum = max(maxSum, currentSum);
            currentSum = nums[i];
        }
    }

    return max(maxSum, currentSum);
}
```


```java
public int numOfWays(int m, int n) {
    long mod = 1000000007;
    long a = 6, b = 6, c = 3, d = 3;
    while (--n > 0) {
        long temp_a = a, temp_c = c;
        a = (a * 3 + b * 2) % mod;
        b = (temp_a * 2 + b * 2) % mod;
        c = (c * 3 + d * 2) % mod;
        d = (temp_c * 2 + d * 2) % mod;
    }
    return (int)(m == 1 ? b : (a + c) % mod);
}
```

```python
def numOfWays(m, n):
    mod = 1000000007
    a, b, c, d = 6, 6, 3, 3
    while n > 1:
        n -= 1
        temp_a = a
        temp_c = c
        a = (a * 3 + b * 2) % mod
        b = (temp_a * 2 + b * 2) % mod
        c = (c * 3 + d * 2) % mod
        d = (temp_c * 2 + d * 2) % mod
    return b if m == 1 else (a + c) % mod
```


```python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def canMerge(trees):
    leaf_count = {}
    root_map = {}

    for tree in trees:
        if tree.left:
            leaf_count[tree.left.val] = leaf_count.get(tree.left.val, 0) + 1
        if tree.right:
            leaf_count[tree.right.val] = leaf_count.get(tree.right.val, 0) + 1
        root_map[tree.val] = tree

    def is_valid_bst(node, min_val, max_val):
        if not node:
            return True
        if node.val <= min_val or node.val >= max_val:
            return False
        if node.left and node.left.val in root_map:
            left_child = root_map.pop(node.left.val)
            leaf_count[tree.left.val] -= 1
            tree.left = left_child
        if node.right and node.right.val in root_map:
            right_child = root_map.pop(node.right.val)
            leaf_count[tree.right.val] -= 1
            tree.right = right_child
        return is_valid_bst(node.left, min_val, node.val) and is_valid_bst(node.right, node.val, max_val)

    for tree in trees:
        if leaf_count.get(tree.val, 0) == 0:
            if is_valid_bst(tree, 0, 5e4 + 1):
                return tree
            break

    return None
```

```cpp
struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

TreeNode* canMerge(vector<TreeNode*>& trees) {
    unordered_map<int, int> leafCount;
    unordered_map<int, TreeNode*> rootMap;
    for (TreeNode* tree : trees) {
        if (tree->left) {
            leafCount[tree->left->val]++;
        }
        if (tree->right) {
            leafCount[tree->right->val]++;
        }
        rootMap[tree->val] = tree;
    }

    function<bool(TreeNode*, int, int)> isValidBST = [&](TreeNode* node, int minVal, int maxVal) {
        if (!node) {
            return true;
        }
        if (node->val <= minVal || node->val >= maxVal) {
            return false;
        }
        return isValidBST(node->left, minVal, node->val) && isValidBST(node->right, node->val, maxVal);
    };

    for (TreeNode* tree : trees) {
        if (leafCount[tree->val] == 0) {
            if (isValidBST(tree, 0, 5e4 + 1)) {
                return tree;
            }
            break;
        }
    }
    return NULL;
}
```


```cpp
int maxPoints(vector<vector<int>>& points) {
    int m = points.size(), n = points[0].size();
    vector<long> dp(n, 0);
    for (auto& row : points) {
        vector<long> next_dp(n, 0);
        for (int c1 = 0; c1 < n; ++c1) {
            long score = dp[c1] + row[c1] - c1;
            for (int c2 = 0; c2 < n; ++c2) {
                next_dp[c2] = max(next_dp[c2], score - row[c1] + c2);
            }
        }
        dp.swap(next_dp);
    }
    return *max_element(dp.begin(), dp.end());
}
```

```java
public int maxPoints(int[][] points) {
    int m = points.length, n = points[0].length;
    long[] dp = new long[n];
    for (int[] row : points) {
        long[] next_dp = new long[n];
        for (int c1 = 0; c1 < n; ++c1) {
            long score = dp[c1] + row[c1] - c1;
            for (int c2 = 0; c2 < n; ++c2) {
                next_dp[c2] = Math.max(next_dp[c2], score - row[c1] + c2);
            }
        }
        dp = next_dp;
    }
    long max_points = 0;
    for (long score : dp) {
        max_points = Math.max(max_points, score);
    }
    return (int) max_points;
}
```


```python
def make_string_sorted(s):
    mod = 1000000007
    n = len(s)
    fact = [1] * (n + 1)
    inv = [1] * (n + 1)
    for i in range(1, n + 1):
        fact[i] = fact[i - 1] * i % mod
        inv[i] = inv[i - 1] * (mod - mod // i) % mod

    ans = 0
    for i in range(n):
        less_than = 0
        for j in range(i + 1, n):
            if s[j] < s[i]:
                less_than += 1
        ans = (ans + less_than * fact[n - i - 1]) % mod
    return ans
```

```java
public int makeStringSorted(String s) {
    final int mod = 1000000007;
    int n = s.length();
    int[] fact = new int[n + 1];
    int[] inv = new int[n + 1];
    fact[0] = inv[0] = 1;
    for (int i = 1; i <= n; ++i) {
        fact[i] = (int)((1L * fact[i - 1] * i) % mod);
        inv[i] = (int)((1L * inv[i - 1] * (mod - mod / i)) % mod);
    }
    int ans = 0;
    for (int i = 0; i < n; ++i) {
        int less_than = 0;
        for (int j = i + 1; j < n; ++j) {
            if (s.charAt(j) < s.charAt(i)) ++less_than;
        }
        ans = (int)((ans + 1L * less_than * fact[n - i - 1]) % mod);
    }
    return ans;
}
```


```python
def splitPainting(segments):
    line = {}
    for s in segments:
        start, end, color = s
        if start not in line:
            line[start] = 0
        if end not in line:
            line[end] = 0
        line[start] += color
        line[end] -= color
    res = []
    pre = 0
    sum = 0
    for key in sorted(line.keys()):
        if pre > 0:
            if sum > 0:
                res.append([pre, key, sum])
        pre = key
        sum += line[key]
    return res
```

```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public List<List<Integer>> splitPainting(int[][] segments) {
    TreeMap<Integer, Integer> line = new TreeMap<>();
    for (int[] s : segments) {
        int start = s[0];
        int end = s[1];
        int color = s[2];
        line.put(start, line.getOrDefault(start, 0) + color);
        line.put(end, line.getOrDefault(end, 0) - color);
    }
    List<List<Integer>> res = new ArrayList<>();
    int pre = 0, sum = 0;
    for (Map.Entry<Integer, Integer> entry : line.entrySet()) {
        if (pre > 0) {
            if (sum > 0) {
                List<Integer> temp = new ArrayList<>();
                temp.add(pre);
                temp.add(entry.getKey());
                temp.add(sum);
                res.add(temp);
            }
        }
        pre = entry.getKey();
        sum += entry.getValue();
    }
    return res;
}
```


```java
public int signFunc(int x) {
    if (x > 0) return 1;
    if (x < 0) return -1;
    return 0;
}

public int arraySign(int[] nums) {
    int product = 1;
    for (int x : nums) {
        product *= x;
    }
    return signFunc(product);
}
```

```python
def sign_func(x):
    if x > 0:
        return 1
    elif x < 0:
        return -1
    else:
        return 0

def array_sign(nums):
    product = 1
    for x in nums:
        product *= x
    return sign_func(product)
```


 false
Explantion: 2 has only two divisors: 1 and 2.

```cpp
int minSideJumps(vector<int>& obstacles) {
    vector<vector<int>> dp(obstacles.size(), vector<int>(3, obstacles.size()));
    dp[0][1] = 0;
    dp[0][0] = 1;
    dp[0][2] = 1;

    for (size_t i = 1; i < obstacles.size(); ++i) {
        if (obstacles[i] != 1) dp[i][0] = min(dp[i-1][0], min(dp[i-1][1] + 1, dp[i-1][2] + 1));
        if (obstacles[i] != 2) dp[i][1] = min(dp[i-1][1], min(dp[i-1][0] + 1, dp[i-1][2] + 1));
        if (obstacles[i] != 3) dp[i][2] = min(dp[i-1][2], min(dp[i-1][0] + 1, dp[i-1][1] + 1));
    }
    return min(dp.back()[0], min(dp.back()[1], dp.back()[2]));
}
```


```python
def minSpaceWastedKResizing(nums, k):
    n = len(nums)
    dp = [[float('inf')] * (k + 1) for _ in range(n + 1)]
    sum_nums = [0] * (n + 1)
    dp[0][0] = 0

    for i in range(1, n + 1):
        sum_nums[i] = sum_nums[i - 1] + nums[i - 1]
        max_val = nums[i - 1]
        for j in range(i - 1, -1, -1):
            max_val = max(max_val, nums[j])
            waste = max_val * (i - j) - (sum_nums[i] - sum_nums[j])
            for c in range(k):
                dp[i][c + 1] = min(dp[i][c + 1], dp[j][c] + waste)

    return dp[n][k]
```

```java
public int minSpaceWastedKResizing(int[] nums, int k) {
    int n = nums.length;
    int[][] dp = new int[n + 1][k + 1];
    int[] sum = new int[n + 1];

    for (int i = 0; i <= n; i++) {
        Arrays.fill(dp[i], Integer.MAX_VALUE / 3);
    }

    dp[0][0] = 0;
    for (int i = 1; i <= n; i++) {
        sum[i] = sum[i - 1] + nums[i - 1];
        int max_val = nums[i - 1];
        for (int j = i - 1; j >= 0; j--) {
            max_val = Math.max(max_val, nums[j]);
            int waste = max_val * (i - j) - (sum[i] - sum[j]);
            for (int c = 0; c < k; c++) {
                dp[i][c + 1] = Math.min(dp[i][c + 1], dp[j][c] + waste);
            }
        }
    }
    return dp[n][k];
}
```