```java
import java.util.ArrayList;

public ArrayList<ArrayList<Integer>> largestMatrix(int[][] grid) {
    int n = grid.length;
    ArrayList<ArrayList<Integer>> maxLocal = new ArrayList<>();

    for (int i = 1; i < n - 1; ++i) {
        maxLocal.add(new ArrayList<>());
        for (int j = 1; j < n - 1; ++j) {
            int max_val = grid[i - 1][j - 1];
            for (int x = -1; x <= 1; ++x) {
                for (int y = -1; y <= 1; ++y) {
                    max_val = Math.max(max_val, grid[i + x][j + y]);
                }
            }
            maxLocal.get(i - 1).add(max_val);
        }
    }

    return maxLocal;
}
```

```python
def largest_matrix(grid):
    n = len(grid)
    maxLocal = [[0] * (n - 2) for _ in range(n - 2)]

    for i in range(1, n - 1):
        for j in range(1, n - 1):
            max_val = grid[i - 1][j - 1]
            for x in range(-1, 2):
                for y in range(-1, 2):
                    max_val = max(max_val, grid[i + x][j + y])
            maxLocal[i - 1][j - 1] = max_val

    return maxLocal
```


```java
public int highestEdgeScoreNode(int[] edges) {
    int[] scores = new int[edges.length];

    for (int i = 0; i < edges.length; i++) {
        scores[edges[i]] += i;
    }

    int maxIndex = 0;
    for (int i = 1; i < scores.length; i++) {
        if (scores[i] > scores[maxIndex]) {
            maxIndex = i;
        }
    }

    return maxIndex;
}
```

```cpp
int highestEdgeScoreNode(vector<int>& edges) {
    vector<int> scores(edges.size(), 0);
    for (int i = 0; i < edges.size(); ++i) {
        scores[edges[i]] += i;
    }
    return max_element(scores.begin(), scores.end()) - scores.begin();
}
```


```java
public int maxWeight(int[][] edges) {
    int n = edges.length;
    int[][] dp = new int[n][2];

    class Helper {
        void dfs(int node) {
            for (int i = 1; i < n; ++i) {
                if (edges[i][0] == node) {
                    dfs(i);
                    dp[node][0] += Math.max(dp[i][0], dp[i][1]);
                    dp[node][1] += dp[i][0];
                }
            }
            dp[node][1] += edges[node][1];
        }
    }
    Helper helper = new Helper();
    helper.dfs(0);

    return Math.max(dp[0][0], dp[0][1]);
}
```

```python
def maxWeight(self, edges):
    n = len(edges)
    dp = [[0] * 2 for _ in range(n)]

    def dfs(node):
        for i in range(1, n):
            if edges[i][0] == node:
                dfs(i)
                dp[node][0] += max(dp[i][0], dp[i][1])
                dp[node][1] += dp[i][0]
        dp[node][1] += edges[node][1]

    dfs(0)
    return max(dp[0][0], dp[0][1])
```


```python
def min_operations(blocks, k):
    n = len(blocks)
    res = k
    w = b = 0
    i = j = 0

    while j < n:
        if blocks[j] == 'W':
            w += 1
        while b > k or (b == k and blocks[i] == 'B'):
            if blocks[i] == 'W':
                w -= 1
                i += 1
            else:
                b -= 1
                i += 1
        if b == k:
            res = min(res, w)
        else:
            b += 1
        j += 1

    return res
```

```java
int minOperations(String blocks, int k) {
    int n = blocks.length(), res = k, w = 0, b = 0;
    for (int i = 0, j = 0; j < n; ++j) {
        if (blocks.charAt(j) == 'W') w++;
        while (b > k || (b == k && blocks.charAt(i) == 'B')) {
            if (blocks.charAt(i++) == 'W') w--;
            else b--;
        }
        if (b == k) res = Math.min(res, w);
        else b++;
    }
    return res;
}
```


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

string shiftCharacters(string s, vector<vector<int>>& shifts) {
    vector<int> shiftValues(s.size(), 0);
    for (const auto &shift : shifts) {
        int start = shift[0], end = shift[1], direction = shift[2];
        int value = (direction == 1) ? 1 : -1;
        shiftValues[start] += value;
        if (end + 1 < s.size()) shiftValues[end + 1] -= value;
    }

    for (int i = 1; i < s.size(); i++) {
        shiftValues[i] += shiftValues[i - 1];
    }

    for (int i = 0; i < s.size(); i++) {
        s[i] = (s[i] - 'a' + shiftValues[i]) % 26 + 'a';
    }

    return s;
}
```

c bcc v l abd q j n i qsu w ppp p aab m t b acd g a `ac d ace e k x jjj `ab y bbb r fff h bbc moq xxx wy egi ace f u z o s bcd

```java
public String shiftCharacters(String s, int[][] shifts) {
    int[] shiftValues = new int[s.length()];
    for (int[] shift : shifts) {
        int start = shift[0], end = shift[1], direction = shift[2];
        int value = (direction == 1) ? 1 : -1;
        shiftValues[start] += value;
        if (end + 1 < s.length()) shiftValues[end + 1] -= value;
    }

    for (int i = 1; i < s.length(); i++) {
        shiftValues[i] += shiftValues[i - 1];
    }

    char[] sArray = s.toCharArray();
    for (int i = 0; i < s.length(); i++) {
        sArray[i] = (char) ((sArray[i] - 'a' + shiftValues[i]) % 26 + 'a');
    }

    return new String(sArray);
}
```


```java
import java.util.*;

public class Solution {
    public int[] maxSegSumAfterQueries(int[] nums, int[] removeQueries) {
        int n = nums.length;
        int[] answer = new int[n];
        TreeSet<Integer> removed = new TreeSet<>();
        removed.add(-1);
        removed.add(n);

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

        for (int i = 0; i < n; ++i) {
            int removeIdx = removeQueries[i];
            answer[i] = maxSum;
            nums[removeIdx] = -nums[removeIdx];

            int leftIdx = removed.higher(removeIdx);
            int rightIdx = removed.lower(removeIdx);

            int leftSum = 0, rightSum = 0;
            for (int j = leftIdx - 1; j >= 0; --j) {
                if (nums[j] < 0) leftSum -= nums[j];
                else break;
            }
            for (int j = rightIdx + 1; j < n; ++j) {
                if (nums[j] < 0) rightSum -= nums[j];
                else break;
            }

            maxSum -= Math.max(0, leftSum - (-nums[removeIdx]));
            maxSum -= Math.max(0, rightSum - (-nums[removeIdx]));
            maxSum += Math.max(0, leftSum + rightSum - (-nums[removeIdx]));

            removed.add(removeIdx);
        }

        return answer;
    }
}
```

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

vector<int> maxSegSumAfterQueries(vector<int>& nums, vector<int>& removeQueries) {
    int n = nums.size();
    vector<int> answer(n);
    set<int> removed;
    removed.insert(-1);
    removed.insert(n);

    int currentSum = 0, maxSum = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] > 0) currentSum += nums[i];
        else {
            maxSum = max(maxSum, currentSum);
            currentSum = 0;
        }
    }
    maxSum = max(maxSum, currentSum);

    for (int i = 0; i < n; ++i) {
        int removeIdx = removeQueries[i];
        answer[i] = maxSum;
        nums[removeIdx] = -nums[removeIdx];

        int leftIdx = *removed.upper_bound(removeIdx);
        int rightIdx = *prev(removed.upper_bound(removeIdx));

        int leftSum = 0, rightSum = 0;
        for (int j = leftIdx - 1; j >= 0; --j) {
            if (nums[j] < 0) leftSum -= nums[j];
            else break;
        }
        for (int j = rightIdx + 1; j < n; ++j) {
            if (nums[j] < 0) rightSum -= nums[j];
            else break;
        }

        maxSum -= max(0, leftSum - (-nums[removeIdx]));
        maxSum -= max(0, rightSum - (-nums[removeIdx]));
        maxSum += max(0, leftSum + rightSum - (-nums[removeIdx]));

        removed.insert(removeIdx);
    }

    return answer;
}
```


```java
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

int timeToInfect(TreeNode node, int start, int minutes) {
    if (node == null) return 0;
    if (node.val == start) return minutes;
    return Math.max(timeToInfect(node.left, start, minutes+1),
                    timeToInfect(node.right, start, minutes+1));
}

int totalInfectionTime(TreeNode root, int total_minutes) {
    if (root == null) return total_minutes;
    int time_needed = Math.max(Math.max(total_minutes,
                                  timeToInfect(root, root.val, 0)),
               Math.max(totalInfectionTime(root.left, total_minutes + 1),
                        totalInfectionTime(root.right, total_minutes + 1)));
    return time_needed;
}
```

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

def time_to_infect(node, start, minutes):
    if not node:
        return 0
    if node.val == start:
        return minutes
    return max(time_to_infect(node.left, start, minutes+1),
               time_to_infect(node.right, start, minutes+1))

def total_infection_time(root, total_minutes=0):
    if not root:
        return total_minutes
    time_needed = max(total_minutes,
                      time_to_infect(root, root.val, 0),
                      total_infection_time(root.left, total_minutes + 1),
                      total_infection_time(root.right, total_minutes + 1))
    return time_needed
```


```python
def kSum(nums, k):
    sums = [0]
    for num in nums:
        if num > 0:
            sums.extend([s + num for s in sums])
            sums.sort(reverse=True)
        else:
            sums.append(num)

    return sums[k - 1]
```

```java
import java.util.ArrayList;
import java.util.Collections;

public class Solution {
    public int kSum(int[] nums, int k) {
        ArrayList<Integer> sums = new ArrayList<>();
        sums.add(0);
        for (int num : nums) {
            if (num > 0) {
                for (int i = sums.size() - 1; i >= 0; i--) {
                    sums.add(sums.get(i) + num);
                }
                sums.sort(Collections.reverseOrder());
            } else {
                sums.add(num);
            }
        }

        return sums.get(k - 1);
    }
}
```


```java
import java.util.Arrays;

public int[] maxSizeSubsequenceSumQueries(int[] nums, int[] queries) {
    Arrays.sort(nums);
    int[] prefixSums = new int[nums.length + 1];
    for (int i = 0; i < nums.length; ++i) {
        prefixSums[i + 1] = prefixSums[i] + nums[i];
    }

    int[] answer = new int[queries.length];
    for (int i = 0; i < queries.length; ++i) {
        int idx = Arrays.binarySearch(prefixSums, queries[i]);
        if (idx < 0) {
            idx = -idx - 1;
        }
        answer[i] = idx - 1;
    }

    return answer;
}
```

```python
from bisect import bisect

def maxSizeSubsequenceSumQueries(nums, queries):
    nums.sort()
    prefixSums = [0] * (len(nums) + 1)
    for i, x in enumerate(nums):
        prefixSums[i + 1] = prefixSums[i] + x

    answer = []
    for q in queries:
        idx = bisect(prefixSums, q)
        answer.append(idx - 1)

    return answer
```


```java
public String removeStars(String s) {
    StringBuilder result = new StringBuilder();
    for (char c : s.toCharArray()) {
        if (c == '*') {
            if (result.length() > 0) {
                result.deleteCharAt(result.length() - 1);
            }
        } else {
            result.append(c);
        }
    }
    return result.toString();
}
```

c bc c c c c c c ac c c ab c abc leet\\cod\e c c c c c c c c a c c c c

```python
def remove_stars(s: str) -> str:
    result = []
    for c in s:
        if c == '*':
            if result:
                result.pop()
        else:
            result.append(c)
    return ''.join(result)
```


```java
public int min_minutes(String[] garbage, int[] travel) {
    int[] time_garbage = new int[3];
    int[] time_travel = new int[3];

    for (int i = 0; i < garbage.length; i++) {
        int m = 0, p = 0, g = 0;
        for (char c : garbage[i].toCharArray()) {
            if (c == 'M') m++;
            else if (c == 'P') p++;
            else g++;
        }
        time_garbage[0] += m;
        time_garbage[1] += p;
        time_garbage[2] += g;
        if (i < garbage.length - 1) {
            time_travel[0] += travel[i];
            time_travel[1] += travel[i];
            time_travel[2] += travel[i];
        }
    }
    return time_garbage[0] + time_travel[0] + time_garbage[1] + time_travel[1] + time_garbage[2] + time_travel[2];
}
```

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

int min_minutes(const vector<string>& garbage, const vector<int>& travel) {
    vector<int> time_garbage(3, 0);
    vector<int> time_travel(3, 0);

    for (int i = 0; i < garbage.size(); i++) {
        int m = 0, p = 0, g = 0;
        for (char c : garbage[i]) {
            if (c == 'M') m++;
            else if (c == 'P') p++;
            else g++;
        }
        time_garbage[0] += m;
        time_garbage[1] += p;
        time_garbage[2] += g;
        if (i < garbage.size() - 1) {
            time_travel[0] += travel[i];
            time_travel[1] += travel[i];
            time_travel[2] += travel[i];
        }
    }
    return time_garbage[0] + time_travel[0] + time_garbage[1] + time_travel[1] + time_garbage[2] + time_travel[2];
}
```


```python
def equal_sum_subarrays(nums):
    sums = set()
    for i in range(1, len(nums)):
        current_sum = nums[i] + nums[i - 1]
        if current_sum in sums:
            return True
        sums.add(current_sum)
    return False
```

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

```java
public boolean equalSumSubarrays(int[] nums) {
    Set<Integer> sums = new HashSet<>();
    for (int i = 1; i < nums.length; ++i) {
        int sum = nums[i] + nums[i - 1];
        if (sums.contains(sum)) return true;
        sums.add(sum);
    }
    return false;
}
```


```java
public boolean isPalindrome(String s) {
    int start = 0;
    int end = s.length() - 1;
    while (start < end) {
        if (s.charAt(start) != s.charAt(end)) {
            return false;
        }
        start++;
        end--;
    }
    return true;
}

public String toBaseString(int n, int base) {
    StringBuilder sb = new StringBuilder();
    while (n > 0) {
        sb.append(n % base);
        n /= base;
    }
    return sb.reverse().toString();
}

public boolean isStrictlyPalindromic(int n) {
    for (int b = 2; b <= n - 2; b++) {
        if (!isPalindrome(toBaseString(n, b))) {
            return false;
        }
    }
    return true;
}
```

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

```cpp
bool is_palindrome(const std::string& s) {
    return std::equal(s.begin(), s.end(), s.rbegin());
}

std::string to_base_str(int n, int base) {
    std::string s;
    while (n > 0) {
        s.push_back(n % base);
        n /= base;
    }
    return s;
}

bool isStrictlyPalindromic(int n) {
    for (int b = 2; b <= n - 2; b++) {
        if (!is_palindrome(to_base_str(n, b))) {
            return false;
        }
    }
    return true;
}
```


```java
import java.util.*;

public int maxCoveredRows(int[][] matrix, int numSelect) {
    int m = matrix.length;
    int n = matrix[0].length;
    int maxCovered = 0;

    for (int i = 0; i < (1 << n); ++i) {
        if (Integer.bitCount(i) == numSelect) {
            int covered = 0;
            for (int row = 0; row < m; ++row) {
                for (int col = 0; col < n; ++col) {
                    if ((matrix[row][col] == 1) && ((i & (1 << col)) > 0)) {
                        covered++;
                        break;
                    }
                }
            }
            maxCovered = Math.max(maxCovered, covered);
        }
    }
    return maxCovered;
}
```

```python
def max_covered_rows(matrix, num_select):
    m, n = len(matrix), len(matrix[0])
    max_covered = 0
    for i in range(1 << n):
        if bin(i).count('1') == num_select:
            covered = 0
            for row in range(m):
                for col in range(n):
                    if matrix[row][col] == 1 and i & (1 << col):
                        covered += 1
                        break
            max_covered = max(max_covered, covered)
    return max_covered
```


```python
MOD = 10**9 + 7
MAX = 1001

def ways(startPos, endPos, k, dp):
    if k == 0: return 1 if startPos == endPos else 0
    if startPos < 0 or endPos < 0 or startPos >= MAX or endPos >= MAX: return 0

    if dp[startPos][k] != -1: return dp[startPos][k]

    left = ways(startPos - 1, endPos, k - 1, dp)
    right = ways(startPos + 1, endPos, k - 1, dp)

    dp[startPos][k] = (left + right) % MOD
    return dp[startPos][k]

def numberOfWays(startPos, endPos, k):
    dp = [[-1 for _ in range(k + 1)] for _ in range(MAX)]
    return ways(startPos, endPos, k, dp)
```

```cpp
const int MOD = 1e9 + 7;
const int MAX = 1001;

int ways(int startPos, int endPos, int k, vector<vector<int>>& dp) {
    if (k == 0) return startPos == endPos;
    if (startPos < 0 || endPos < 0 || startPos >= MAX || endPos >= MAX) return 0;

    if (dp[startPos][k] != -1) return dp[startPos][k];

    int left = ways(startPos - 1, endPos, k - 1, dp);
    int right = ways(startPos + 1, endPos, k - 1, dp);

    return dp[startPos][k] = (left + right) % MOD;
}

int numberOfWays(int startPos, int endPos, int k) {
    vector<vector<int>> dp(MAX, vector<int>(k + 1, -1));
    return ways(startPos, endPos, k, dp);
}
```


```java
public int longestNiceSubarray(int[] nums) {
    int n = nums.length;
    int maxLen = 1;
    for (int i = 0; i < n; i++) {
        int mask = 0;
        for (int j = i; j < n; j++) {
            mask |= nums[j];
            if ((mask & (mask - 1)) == 0) {
                maxLen = Math.max(maxLen, j - i + 1);
            }
        }
    }
    return maxLen;
}
```

```cpp
int longestNiceSubarray(vector<int>& nums) {
    int n = nums.size();
    int max_len = 1;
    for (int i = 0; i < n; ++i) {
        int mask = 0;
        for (int j = i; j < n; ++j) {
            mask |= nums[j];
            if ((mask & (mask - 1)) == 0) {
                max_len = max(max_len, j - i + 1);
            }
        }
    }
    return max_len;
}
```


```java
import java.util.Arrays;
import java.util.PriorityQueue;

public int mostVisitedRoom(int n, int[][] meetings) {
    Arrays.sort(meetings, (a, b) -> Integer.compare(a[0], b[0]));
    PriorityQueue<int[]> pq = new PriorityQueue<>(((a, b) -> Integer.compare(a[0], b[0])));
    int[] rooms = new int[n];

    for (int[] meeting : meetings) {
        while (!pq.isEmpty() && pq.peek()[0] <= meeting[0]) {
            rooms[pq.poll()[1]]++;
        }
        pq.offer(new int[] {meeting[1], pq.size() % n});
    }
    int result = 0;
    for (int i = 1; i < n; i++) {
        if (rooms[i] > rooms[result]) {
            result = i;
        }
    }
    return result;
}
```

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

int mostVisitedRoom(int n, std::vector<std::vector<int>>& meetings) {
    std::sort(meetings.begin(), meetings.end());
    std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, std::greater<>> pq;
    std::vector<int> rooms(n);

    for (const auto& meeting : meetings) {
        while (!pq.empty() && pq.top().first <= meeting[0]) {
            ++rooms[pq.top().second];
            pq.pop();
        }
        pq.push({meeting[1], pq.size() % n});
    }
    int result = 0;
    for (int i = 1; i < n; ++i) {
        if (rooms[i] > rooms[result]) {
            result = i;
        }
    }
    return result;
}
```


```cpp
int min_days(const std::vector<int>& power) {
    int n = power.size();
    int ans = 1e9;
    std::vector<int> dp(1 << n, 1e9);

    dp[0] = 0;
    std::vector<int> sorted_power(power.begin(), power.end());
    sort(sorted_power.begin(), sorted_power.end());

    for (int i = 0; i < (1 << n); ++i) {
        int power_sum = 0;
        for (int j = 0; j < n; ++j) {
            if (i & (1 << j)) {
                power_sum += sorted_power[j];
            }
        }
        int gain = 1 + __builtin_popcount(i);
        for (int j = 0; j < n; ++j) {
            if (!(i & (1 << j)) && gain > sorted_power[j]) {
                dp[i | (1 << j)] = std::min(dp[i | (1 << j)], dp[i] + 1);
            }
        }
    }
    return dp[(1 << n) - 1];
}
```

```java
public int minDays(int[] power) {
    int n = power.length;
    int ans = (int)1e9;
    int[] dp = new int[1 << n];
    Arrays.fill(dp, (int)1e9);

    dp[0] = 0;
    int[] sortedPower = Arrays.copyOf(power, n);
    Arrays.sort(sortedPower);

    for (int i = 0; i < (1 << n); ++i) {
        int powerSum = 0;
        for (int j = 0; j < n; ++j) {
            if ((i & (1 << j)) != 0) {
                powerSum += sortedPower[j];
            }
        }
        int gain = 1 + Integer.bitCount(i);
        for (int j = 0; j < n; ++j) {
            if ((i & (1 << j)) == 0 && gain > sortedPower[j]) {
                dp[i | (1 << j)] = Math.min(dp[i | (1 << j)], dp[i] + 1);
            }
        }
    }
    return dp[(1 << n) - 1];
}
```


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

int minGroups(vector<vector<int>>& intervals) {
    sort(intervals.begin(), intervals.end());
    priority_queue<int, vector<int>, greater<int>> pq;
    for (auto& interval : intervals) {
        if (!pq.empty() && pq.top() < interval[0]) {
            pq.pop();
        }
        pq.push(interval[1]);
    }
    return pq.size();
}
```

```java
import java.util.Arrays;
import java.util.PriorityQueue;

public int minGroups(int[][] intervals) {
    Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
    PriorityQueue<Integer> pq = new PriorityQueue<>();
    for (int[] interval : intervals) {
        if (!pq.isEmpty() && pq.peek() < interval[0]) {
            pq.poll();
        }
        pq.offer(interval[1]);
    }
    return pq.size();
}
```


```cpp
int longestSubsequence(vector<int>& nums, int k) {
    int n = nums.size();
    map<int, int> dp;
    int ans = 0;

    for (int num : nums) {
        int temp = 0;
        auto it = dp.upper_bound(num - k - 1);
        if (it != dp.begin()) {
            --it;
            temp = it->second;
        }
        dp[num] = max(dp[num], temp + 1);
        ans = max(ans, dp[num]);
    }

    return ans;
}
```

```java
public int longestSubsequence(int[] nums, int k) {
    int n = nums.length;
    TreeMap<Integer, Integer> dp = new TreeMap<>();
    int ans = 0;

    for (int num : nums) {
        int temp = 0;
        Integer key = dp.lowerKey(num - k);
        if (key != null) {
            temp = dp.get(key);
        }
        dp.put(num, Math.max(dp.getOrDefault(num, 0), temp + 1));
        ans = Math.max(ans, dp.get(num));
    }

    return ans;
}
```


```python
def max_matchings(players, trainers):
    players.sort()
    trainers.sort()

    player_index, trainer_index, match_count = 0, 0, 0
    while (player_index < len(players)) and (trainer_index < len(trainers)):
        if players[player_index] <= trainers[trainer_index]:
            match_count += 1
            player_index += 1
            trainer_index += 1
        else:
            trainer_index += 1

    return match_count
```

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

int maxMatchings(std::vector<int>& players, std::vector<int>& trainers) {
    std::sort(players.begin(), players.end());
    std::sort(trainers.begin(), trainers.end());

    int playerIndex = 0, trainerIndex = 0, matchCount = 0;
    while (playerIndex < players.size() && trainerIndex < trainers.size()) {
        if (players[playerIndex] <= trainers[trainerIndex]) {
            matchCount++;
            playerIndex++;
            trainerIndex++;
        } else {
            trainerIndex++;
        }
    }

    return matchCount;
}
```


```python
def min_money(transactions):
    min_money_needed = 0
    for transaction in transactions:
        min_money_needed = max(min_money_needed, transaction[0] - transaction[1])
    return min_money_needed
```

```cpp
int min_money(vector<vector<int>>& transactions) {
    int min_money_needed = 0;
    for (const auto& transaction : transactions) {
        min_money_needed = max(min_money_needed, transaction[0] - transaction[1]);
    }
    return min_money_needed;
}
```


```cpp
int smallestMultiple(int n) {
    return n % 2 == 0 ? n : n * 2;
}
```

```python
def smallest_multiple(n):
    return n if n % 2 == 0 else n * 2
```


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

def reverse_odd_levels(node, level):
    if node is None: return
    if level % 2 == 1:
        node.left, node.right = node.right, node.left
    reverse_odd_levels(node.left, level + 1)
    reverse_odd_levels(node.right, level + 1)

def reverse_odd_level_nodes(root):
    reverse_odd_levels(root, 0)
    return root
```

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

public void reverseOddLevels(TreeNode node, int level) {
    if (node == null) return;
    if (level % 2 == 1) {
        TreeNode temp = node.left;
        node.left = node.right;
        node.right = temp;
    }
    reverseOddLevels(node.left, level + 1);
    reverseOddLevels(node.right, level + 1);
}

public TreeNode reverseOddLevelNodes(TreeNode root) {
    reverseOddLevels(root, 0);
    return root;
}
```


```python
from collections import defaultdict

def prefix_score_sum(words):
    result = [0] * len(words)
    prefix_count = defaultdict(int)

    for word in words:
        prefix = ""
        for c in word:
            prefix += c
            prefix_count[prefix] += 1

    for i, word in enumerate(words):
        prefix = ""
        for c in word:
            prefix += c
            result[i] += prefix_count[prefix]

    return result
```

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

public List<Integer> prefixScoreSum(List<String> words) {
    List<Integer> result = new ArrayList<>(words.size());
    Map<String, Integer> prefixCount = new HashMap<>();

    for (String word : words) {
        String prefix = "";
        for (char c : word.toCharArray()) {
            prefix += c;
            prefixCount.put(prefix, prefixCount.getOrDefault(prefix, 0) + 1);
        }
    }

    for (String word : words) {
        String prefix = "";
        int sum = 0;
        for (char c : word.toCharArray()) {
            prefix += c;
            sum += prefixCount.getOrDefault(prefix, 0);
        }
        result.add(sum);
    }

    return result;
}
```


```java
public int longestSubarray(int[] nums) {
    int max_and = 0;
    for (int i = 0; i < nums.length; i++) {
        int temp_and = nums[i];
        for (int j = i + 1; j < nums.length; j++) {
            temp_and &= nums[j];
            max_and = Math.max(max_and, temp_and);
        }
    }

    int longest_subarray = 0, current_length = 0;
    for (int i = 0; i < nums.length; i++) {
        int temp_and = nums[i];
        current_length = (temp_and == max_and) ? 1 : 0;
        for (int j = i + 1; j < nums.length; j++) {
            temp_and &= nums[j];
            if (temp_and == max_and) {
                current_length++;
            } else {
                break;
            }
        }
        longest_subarray = Math.max(longest_subarray, current_length);
    }
    return longest_subarray;
}
```

```cpp
int longestSubarray(vector<int>& nums) {
    int max_and = 0;
    for (int i = 0; i < nums.size(); i++) {
        int temp_and = nums[i];
        for (int j = i + 1; j < nums.size(); j++) {
            temp_and &= nums[j];
            max_and = max(max_and, temp_and);
        }
    }

    int longest_subarray = 0, current_length = 0;
    for (int i = 0; i < nums.size(); i++) {
        int temp_and = nums[i];
        current_length = (temp_and == max_and) ? 1 : 0;
        for (int j = i + 1; j < nums.size(); j++) {
            temp_and &= nums[j];
            if (temp_and == max_and) {
                current_length++;
            } else {
                break;
            }
        }
        longest_subarray = max(longest_subarray, current_length);
    }
    return longest_subarray;
}
```


```python
def find_good_indices(nums, k):
    good_indices = []
    for i in range(k, len(nums) - k):
        left_non_inc = all(nums[i - j - 1] >= nums[i - j - 2] for j in range(k - 1))
        right_non_dec = all(nums[i + j + 1] >= nums[i + j + 2] for j in range(k - 1))

        if left_non_inc and right_non_dec:
            good_indices.append(i)

    return good_indices
```

```cpp
#include <vector>

std::vector<int> findGoodIndices(const std::vector<int>& nums, int k) {
    std::vector<int> good_indices;
    for(int i = k; i < nums.size() - k; ++i) {
        bool left_non_inc = true;
        bool right_non_dec = true;

        for(int j = 0; j < k - 1; ++j) {
            if (nums[i - j - 1] < nums[i - j - 2]) {
                left_non_inc = false;
                break;
            }
        }

        for(int j = 0; j < k - 1; ++j) {
            if (nums[i + j + 1] < nums[i + j + 2]) {
                right_non_dec = false;
                break;
            }
        }

        if (left_non_inc && right_non_dec) {
            good_indices.push_back(i);
        }
    }
    return good_indices;
}
```


```python
from collections import defaultdict

def dfs(node, parent, adj, vals, cur_max, count):
    if vals[node] >= cur_max:
        if vals[node] > cur_max:
            count[0] += 1
            cur_max = vals[node]
        for next in adj[node]:
            if next != parent:
                dfs(next, node, adj, vals, cur_max, count)

def number_of_good_paths(vals, edges):
    n = len(vals)
    adj = defaultdict(list)
    for edge in edges:
        adj[edge[0]].append(edge[1])
        adj[edge[1]].append(edge[0])
    count = [0]
    for i in range(n):
        dfs(i, -1, adj, vals, -1, count)
    return count[0]
```

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

void dfs(int node, int parent, const vector<vector<int>>& adj, const vector<int>& vals, int curMax, int& count) {
    if (vals[node] >= curMax) {
        if (vals[node] > curMax) {
            count++;
            curMax = vals[node];
        }
        for (int next : adj[node]) {
            if (next != parent) {
                dfs(next, node, adj, vals, curMax, count);
            }
        }
    }
}

int NumberOfGoodPaths(const vector<int>& vals, const vector<vector<int>>& edges) {
    int n = vals.size();
    vector<vector<int>> adj(n);
    for (const auto& edge : edges) {
        adj[edge[0]].push_back(edge[1]);
        adj[edge[1]].push_back(edge[0]);
    }
    int count = 0;
    for (int i = 0; i < n; i++) {
        dfs(i, -1, adj, vals, -1, count);
    }
    return count;
}
```


```java
public int minOperations(int[] nums) {
    int n = nums.length;
    int i = 0, j = n - 1;
    int operations = 0;

    while (i < j) {
        if (nums[i] == nums[j]) {
            i++;
            j--;
        } else if (nums[i] < nums[j]) {
            nums[i + 1] += nums[i];
            i++;
            operations++;
        } else {
            nums[j - 1] += nums[j];
            j--;
            operations++;
        }
    }
    return operations;
}
```

```python
def minOperations(nums):
    n = len(nums)
    i, j = 0, n - 1
    operations = 0

    while i < j:
        if nums[i] == nums[j]:
            i += 1
            j -= 1
        elif nums[i] < nums[j]:
            nums[i + 1] += nums[i]
            i += 1
            operations += 1
        else:
            nums[j - 1] += nums[j]
            j -= 1
            operations += 1

    return operations
```


```python
def can_equal_frequency(word: str) -> bool:
    freq = {}
    for c in word:
        freq[c] = freq.get(c, 0) + 1

    count_freq = {}
    for f in freq.values():
        count_freq[f] = count_freq.get(f, 0) + 1

    if len(count_freq) != 2:
        return False

    a, acount = next(iter(count_freq.items()))
    b, bcount = next(reversed(list(count_freq.items())))

    return (acount == 1 and (a - 1 == b or a == 1)) or (bcount == 1 and (b - 1 == a or b == 1))
```

abcdeee aaabbc xxy abcd xy xxxxy abcdee abc aabbcc aazz abcdeeee abcde xxyy aabc aaabbbccc abcdee abcc aabbcc xxxy abcdeeeee xyy xxxxx abcdeee aaaaaaabbbbbbbcc xxxxx aabbccdde abcde aabbccdd aabbccdddee abcc aacb aabbccd xxxy xyy abc abcde aabb abcdeeee yxx xyx aabbcc xxxxy aab abcd abcb abcde xyyy aabbccddeeff xyyy abca xxyy abcc xyyz aabbccdddeee aabbccddde

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

```java
import java.util.HashMap;

public boolean canEqualFrequency(String word) {
    HashMap<Character, Integer> freq = new HashMap<>();
    for (char c : word.toCharArray()) {
        freq.put(c, freq.getOrDefault(c, 0) + 1);
    }

    HashMap<Integer, Integer> count_freq = new HashMap<>();
    for (int f : freq.values()) {
        count_freq.put(f, count_freq.getOrDefault(f, 0) + 1);
    }

    if (count_freq.size() != 2) {
        return false;
    }

    int a = (int) count_freq.keySet().toArray()[0];
    int acount = count_freq.get(a);
    int b = (int) count_freq.keySet().toArray()[1];
    int bcount = count_freq.get(b);

    return (acount == 1 && (a - 1 == b || a == 1)) || (bcount == 1 && (b - 1 == a || b == 1));
}
```


```cpp
int getXOR(vector<int>& nums1, vector<int>& nums2) {
    int xor_result = 0;
    for (int num1 : nums1) {
        for (int num2 : nums2) {
            xor_result ^= (num1 ^ num2);
        }
    }
    return xor_result;
}
```

```python
def get_xor(nums1, nums2):
    xor_result = 0
    for num1 in nums1:
        for num2 in nums2:
            xor_result ^= (num1 ^ num2)
    return xor_result
```


```cpp
int countPairs(const vector<int>& nums1, const vector<int>& nums2, int diff) {
    int n = nums1.size(), count = 0;
    for (int i = 0; i < n; i++) {
        for (int j = i + 1; j < n; j++) {
            if (nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff) {
                count++;
            }
        }
    }
    return count;
}
```

```python
def count_pairs(nums1, nums2, diff):
    n = len(nums1)
    count = 0
    for i in range(n):
        for j in range(i + 1, n):
            if nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff:
                count += 1
    return count
```


```cpp
int commonFactors(int a, int b) {
    int gcd = std::__gcd(a, b);
    int count = 0;
    for (int i = 1; i * i <= gcd; i++) {
        if (gcd % i == 0) {
            count++;
            if (i * i != gcd)
                count++;
        }
    }
    return count;
}
```

```python
def common_factors(a: int, b: int) -> int:
    from math import gcd

    g = gcd(a, b)
    count = 0
    for i in range(1, int(g**0.5) + 1):
        if g % i == 0:
            count += 1
            if i * i != g:
                count += 1
    return count
```


```java
public int maxHourglassSum(int[][] grid) {
    int m = grid.length, n = grid[0].length;
    int maxSum = Integer.MIN_VALUE;
    for(int i = 1; i < m - 1; ++i) {
        for(int j = 1; j < n - 1; ++j) {
            int sum = grid[i-1][j-1] + grid[i-1][j] + grid[i-1][j+1]
                      + grid[i][j]
                      + grid[i+1][j-1] + grid[i+1][j] + grid[i+1][j+1];
            maxSum = Math.max(maxSum, sum);
        }
    }
    return maxSum;
}
```

```python
def max_hourglass_sum(grid):
    m, n = len(grid), len(grid[0])
    max_sum = float('-inf')
    for i in range(1, m - 1):
        for j in range(1, n - 1):
            sum = grid[i-1][j-1] + grid[i-1][j] + grid[i-1][j+1] \
                  + grid[i][j] \
                  + grid[i+1][j-1] + grid[i+1][j] + grid[i+1][j+1]
            max_sum = max(max_sum, sum)
    return max_sum
```


```java
public int minSetXor(int num1, int num2) {
    int set_count = Integer.bitCount(num2);
    int x = 0;
    for (int i = 0; set_count > 0 && i < 32; i++) {
        if ((num2 >> i) & 1) {
            x |= (1 << i);
            set_count--;
        }
    }
    return x ^ num1;
}
```

```cpp
int minSetXor(int num1, int num2) {
    int set_count = __builtin_popcount(num2);
    int x = 0;
    for (int i = 0; set_count > 0 && i < 32; i++) {
        if ((num2 >> i) & 1) {
            x |= (1 << i);
            set_count--;
        }
    }
    return x ^ num1;
}
```


```java
public int maxTastiness(int[] price, int[] tastiness, int maxAmount, int maxCoupons) {
    int n = price.length;
    int[][][] dp = new int[n + 1][maxAmount + 1][maxCoupons + 1];

    for (int i = 1; i <= n; i++) {
        int fruit_price = price[i - 1];
        int fruit_tastiness = tastiness[i - 1];
        int half_fruit_price = fruit_price / 2;

        for (int j = 0; j <= maxAmount; j++) {
            for (int k = 0; k <= maxCoupons; k++) {
                dp[i][j][k] = dp[i - 1][j][k];
                if (j >= fruit_price) {
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i - 1][j - fruit_price][k] + fruit_tastiness);
                }
                if (k > 0 && j >= half_fruit_price) {
                    dp[i][j][k] = Math.max(dp[i][j][k], dp[i - 1][j - half_fruit_price][k - 1] + fruit_tastiness);
                }
            }
        }
    }

    return dp[n][maxAmount][maxCoupons];
}
```

price = \[10,20,20\], tastiness = \[5,8,8\], maxAmount = 20, maxCoupons = 1

```cpp
int maxTastiness(vector<int>& price, vector<int>& tastiness, int maxAmount, int maxCoupons) {
    int n = price.size();
    vector<vector<vector<int>>> dp(n + 1, vector<vector<int>>(maxAmount + 1, vector<int>(maxCoupons + 1, 0)));

    for (int i = 1; i <= n; i++) {
        int fruit_price = price[i - 1];
        int fruit_tastiness = tastiness[i - 1];
        int half_fruit_price = fruit_price / 2;

        for (int j = 0; j <= maxAmount; j++) {
            for (int k = 0; k <= maxCoupons; k++) {
                dp[i][j][k] = dp[i - 1][j][k];
                if (j >= fruit_price) {
                    dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - fruit_price][k] + fruit_tastiness);
                }
                if (k > 0 && j >= half_fruit_price) {
                    dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - half_fruit_price][k - 1] + fruit_tastiness);
                }
            }
        }
    }

    return dp[n][maxAmount][maxCoupons];
}
```


```java
public int workerWithLongestTask(int n, int[][] logs) {
    int result = 0;
    int max_time = logs[0][1] - 0;

    for (int i = 1; i < logs.length; ++i) {
        int time = logs[i][1] - logs[i-1][1];
        if (time > max_time) {
            max_time = time;
            result = logs[i][0];
        }
    }
    return result;
}
```

```cpp
int workerWithLongestTask(int n, vector<vector<int>>& logs) {
    int result = 0;
    int max_time = logs[0][1] - 0;

    for (int i = 1; i < logs.size(); ++i) {
        int time = logs[i][1] - logs[i-1][1];
        if (time > max_time) {
            max_time = time;
            result = logs[i][0];
        }
    }
    return result;
}
```


```java
public int[] findArray(int[] pref) {
    int[] arr = new int[pref.length];
    arr[0] = pref[0];
    for (int i = 1; i < pref.length; ++i) {
        arr[i] = pref[i] ^ pref[i - 1];
    }
    return arr;
}
```

```cpp
vector<int> findArray(vector<int>& pref) {
    vector<int> arr(pref.size());
    arr[0] = pref[0];
    for (int i = 1; i < pref.size(); ++i) {
        arr[i] = pref[i] ^ pref[i - 1];
    }
    return arr;
}
```


```cpp
std::string robotSort(std::string s) {
    std::string t;
    for (char c : s) {
        while (!t.empty() && t.back() <= c) {
            t.pop_back();
        }
        t.push_back(c);
    }
    return t;
}
```

iiij klmno ggghhiijjkkklm defg uvwxy abcde sttu bac kkkl bdda mnop qqqrrs ccc gggh fghij zza qrst mmmn abc yz z abzbza ddeeff eeff aabbcc jkkklm zza tuvwx vwxy abc nnooppqqqrrrs aabb z opqr aabbccddeeff xyyz uvwx azbzaz ccdd abcde pqrst hijkl a tuvwx yz yz zza defg nnoopp ggghhi

z e e u za m g n c l f l j g i c y c x x h z za b za d r o z z t p c j m z c z p t da za s f z y f x s a

```python
def robot_sort(s):
    t = []
    for c in s:
        while t and t[-1] <= c:
            t.pop()
        t.append(c)
    return ''.join(t)
```


```java
public int ways(int[][] grid, int m, int n, int i, int j, int k, int sum, int[][][] dp) {
    if (i == m - 1 && j == n - 1) {
        return (sum + grid[i][j]) % k == 0 ? 1 : 0;
    }
    if (dp[i][j][sum] == -1) {
        int ans = 0;
        if (i + 1 < m) ans = (ans + ways(grid, m, n, i + 1, j, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        if (j + 1 < n) ans = (ans + ways(grid, m, n, i, j + 1, k, (sum + grid[i][j]) % k, dp)) % 1000000007;
        dp[i][j][sum] = ans;
    }
    return dp[i][j][sum];
}

public int waysToReachDivisibleSum(int[][] grid, int k) {
    int m = grid.length, n = grid[0].length;
    int[][][] dp = new int[m][n][k];
    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            Arrays.fill(dp[i][j], -1);
        }
    }
    return ways(grid, m, n, 0, 0, k, 0, dp);
}
```

```python
def ways(grid, m, n, i, j, k, sum, dp):
    if i == m - 1 and j == n - 1:
        return 1 if (sum + grid[i][j]) % k == 0 else 0
    if dp[i][j][sum] == -1:
        ans = 0
        if i + 1 < m:
            ans = (ans + ways(grid, m, n, i + 1, j, k, (sum + grid[i][j]) % k, dp)) % 1000000007
        if j + 1 < n:
            ans = (ans + ways(grid, m, n, i, j + 1, k, (sum + grid[i][j]) % k, dp)) % 1000000007
        dp[i][j][sum] = ans
    return dp[i][j][sum]

def waysToReachDivisibleSum(grid, k):
    m, n = len(grid), len(grid[0])
    dp = [[[-1] * k for _ in range(n)] for _ in range(m)]
    return ways(grid, m, n, 0, 0, k, 0, dp)
```


```python
def min_arrays(nums):
    def gcd(a, b):
        return a if b == 0 else gcd(b, a % b)

    total_gcd = nums[0]
    for num in nums[1:]:
        total_gcd = gcd(total_gcd, num)

    return 2 if total_gcd == 1 else 1
```

```java
public int minArrays(int[] nums) {
    int n = nums.length;
    int totalGcd = nums[0];
    for (int i = 1; i < n; ++i) {
        totalGcd = gcd(totalGcd, nums[i]);
    }
    return (totalGcd == 1) ? 2 : 1;
}

public int gcd(int a, int b) {
    return (b == 0) ? a : gcd(b, a % b);
}
```


```cpp
int findMinMaximumValue(vector<int>& nums) {
    int result = nums[0], sum = nums[0];
    for (int i = 1; i < nums.size(); i++) {
        sum += nums[i];
        result = max(result, (sum + i) / (i + 1));
    }
    return result;
}
```

```python
def find_min_maximum_value(nums):
    result = nums[0]
    total_sum = nums[0]
    for i in range(1, len(nums)):
        total_sum += nums[i]
        result = max(result, (total_sum + i) // (i + 1))
    return result
```


```python
from collections import defaultdict

def dfs(node, parent, nums, graph, total, result):
    total_sum = nums[node]
    for neighbor in graph[node]:
        if neighbor != parent:
            total_sum += dfs(neighbor, node, nums, graph, total, result)
    if total_sum == total // 2:
        result.append(1)
        return 0
    return total_sum

def delete_edges_to_balance_tree(nums, edges):
    n = len(nums)
    graph = defaultdict(list)
    for e in edges:
        graph[e[0]].append(e[1])
        graph[e[1]].append(e[0])

    total = sum(nums)
    if total % 2 != 0:
        return 0  # It is impossible to split the tree fairly.

    result = []
    dfs(0, -1, nums, graph, total, result)
    return len(result) - 1
```

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

public int dfs(int node, int parent, int[] nums, List<List<Integer>> graph, int total, int[] result) {
    int sum = nums[node];
    for (int neighbor : graph.get(node)) {
        if (neighbor != parent) {
            sum += dfs(neighbor, node, nums, graph, total, result);
        }
    }
    if (sum == total / 2) {
        result[0]++;
        return 0;
    }
    return sum;
}

public int delete_edges_to_balance_tree(int[] nums, int[][] edges) {
    int n = nums.length;
    List<List<Integer>> graph = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        graph.add(new ArrayList<>());
    }
    for (int[] e : edges) {
        graph.get(e[0]).add(e[1]);
        graph.get(e[1]).add(e[0]);
    }

    int total = 0;
    for (int num : nums) {
        total += num;
    }
    if (total % 2 != 0) {
        return 0;  // It is impossible to split the tree fairly.
    }

    int[] result = {0};
    dfs(0, -1, nums, graph, total, result);
    return result[0] - 1;
}
```


```java
public int findK(int[] nums) {
    Set<Integer> set = new HashSet<>();
    for (int num : nums) {
        set.add(num);
    }
    int k = -1;
    for (int num : nums) {
        if (set.contains(-num)) {
            k = Math.max(k, Math.abs(num));
        }
    }
    return k;
}
```

```cpp
int findK(vector<int>& nums) {
    set<int> s(nums.begin(), nums.end());
    int k = -1;
    for (const int& num : nums) {
        if (s.find(-num) != s.end()) {
            k = max(k, abs(num));
        }
    }
    return k;
}
```


```python
def distinct_integers_after_reversing_and_adding(nums):
    distinct = set(nums)
    for num in nums:
        reversed_num = int(str(num)[::-1])
        distinct.add(reversed_num)
    return len(distinct)
```

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

public int distinctIntegersAfterReversingAndAdding(int[] nums) {
    Set<Integer> distinct = new HashSet<>();
    for (int num : nums) {
        distinct.add(num);
        int reversed = 0;
        while (num > 0) {
            reversed = reversed * 10 + num % 10;
            num /= 10;
        }
        distinct.add(reversed);
    }
    return distinct.size();
}
```


```python
def sum_with_reverse(num: int) -> bool:
    for i in range(num + 1):
        reverse = int(str(i)[::-1])
        if i + reverse == num:
            return True
    return False
```

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

```java
public boolean sumWithReverse(int num) {
    for (int i = 0; i <= num; i++) {
        int reverse = 0, temp = i;
        while (temp != 0) {
            reverse = reverse * 10 + temp % 10;
            temp /= 10;
        }
        if (i + reverse == num) {
            return true;
        }
    }
    return false;
}
```


```python
def fixed_bound_subarrays(nums, minK, maxK):
    count, min_index, max_index = 0, -1, -1
    for i, num in enumerate(nums):
        if num==minK:
            min_index=i
        elif num==maxK:
            max_index=i

        count += min(min_index, max_index) + 1
    return count
```

```cpp
int fixedBoundSubarrays(vector<int>& nums, int minK, int maxK) {
    int count = 0, min_index = -1, max_index = -1;
    for (int i = 0; i < nums.size(); i++) {
        if(nums[i]==minK) min_index=i;
        else if(nums[i]==maxK) max_index=i;
        count += min(min_index, max_index)+1;
    }
    return count;
}
```


```python
def flip_trees(n, queries):
    flipped_nodes = {}
    for query in queries:
        flipped_nodes[query] = not flipped_nodes.get(query, False)
        while query > 1:
            query //= 2
            flipped_nodes[query] = not flipped_nodes.get(query, False)

    count = 0
    for value in flipped_nodes.values():
        if value:
            count += 1

    return count
```

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

public int flipTrees(int n, List<Integer> queries) {
    Map<Integer, Boolean> flippedNodes = new HashMap<>();
    for (int query : queries) {
        flippedNodes.put(query, !flippedNodes.getOrDefault(query, false));
        while (query > 1) {
            query /= 2;
            flippedNodes.put(query, !flippedNodes.getOrDefault(query, false));
        }
    }

    int count = 0;
    for (Map.Entry<Integer, Boolean> node : flippedNodes.entrySet()) {
        if (node.getValue()) {
            count++;
        }
    }
    return count;
}
```


```java
public int gcd(int a, int b) {
    if (b == 0) return a;
    return gcd(b, a % b);
}

public int countGCDSubarrays(int[] nums, int k) {
    int count = 0;

    for (int i = 0; i < nums.length; ++i) {
        int gcdSoFar = 0;
        for (int j = i; j < nums.length; ++j) {
            gcdSoFar = gcd(gcdSoFar, nums[j]);
            if (gcdSoFar == k) ++count;
        }
    }

    return count;
}
```

```python
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

def count_GCD_subarrays(nums, k):
    count = 0

    for i in range(len(nums)):
        gcd_so_far = 0
        for j in range(i, len(nums)):
            gcd_so_far = gcd(gcd_so_far, nums[j])
            if gcd_so_far == k:
                count += 1

    return count
```


```cpp
#include<string>
#include<unordered_set>
#define MOD 1000000007
using namespace std;

int distinctStrings(string s, int k) {
    int n = s.length(), cnt = 0;
    unordered_set<string> st;

    for (int i = 0; i <= n - k; ++i) {
        string temp = s.substr(0, i) + s.substr(i + k);
        if (st.count(temp) == 0) {
            st.insert(temp);
            cnt = (cnt + 1) % MOD;
        }
    }
    return cnt + 1; // Add 1 for the original string
}
```

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

public int distinctStrings(String s, int k) {
    int n = s.length(), cnt = 0;
    Set<String> st = new HashSet<>();

    for (int i = 0; i <= n - k; ++i) {
        String temp = s.substring(0, i) + s.substring(i + k);
        if (!st.contains(temp)) {
            st.add(temp);
            cnt = (cnt + 1) % 1000000007;
        }
    }
    return cnt + 1; // Add 1 for the original string
}
```


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

std::string stringWithDifferentDifference(std::vector<std::string>& words) {
    auto getDifferenceArray = [](const std::string& word) {
        std::vector<int> differenceArray;
        for (size_t i = 1; i < word.size(); i++) {
            differenceArray.push_back(word[i] - word[i - 1]);
        }
        return differenceArray;
    };

    std::vector<std::vector<int>> diffArrays;
    for (const auto& word : words) {
        diffArrays.push_back(getDifferenceArray(word));
    }

    int oddArrayIndex = -1;
    for (int i = 1; i < diffArrays.size(); i++) {
        int matchCount = 0;
        for (int j = 0; j < diffArrays[i].size(); j++) {
            if (diffArrays[0][j] == diffArrays[i][j]) {
                matchCount++;
            }
        }

        if (matchCount == 0) {
            oddArrayIndex = i;
            break;
        }
    }

    return words[oddArrayIndex];
}
```

yz zwxv pqr ghi xyzaff wvu pqr pqr wvu yz yz pqr ghi aaa wvu ghi pqr zcde yz adc ghi abc wvu yz yz cdefg pqr wvu ghi stuvw mno ghi wvu pqr ghi pqr wvu yz yz b

```python
def stringWithDifferentDifference(words):
    def get_difference_array(word):
        return [ord(word[i+1]) - ord(word[i]) for i in range(len(word) - 1)]

    diffArrays = [get_difference_array(word) for word in words]

    oddArrayIndex = -1
    for i in range(1, len(diffArrays)):
        matchCount = sum(diffArrays[0][j] == diffArrays[i][j] for j in range(len(diffArrays[i])))
        if matchCount == 0:
            oddArrayIndex = i
            break

    return words[oddArrayIndex]
```


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

public int countDifferences(String a, String b) {
    int diff = 0;
    for (int i = 0; i < a.length(); ++i) {
        if (a.charAt(i) != b.charAt(i)) {
            ++diff;
        }
    }
    return diff;
}

public List<String> findMatchingWords(String[] queries, String[] dictionary) {
    ArrayList<String> result = new ArrayList<>();
    for (String query : queries) {
        for (String dictWord : dictionary) {
            if (countDifferences(query, dictWord) <= 2) {
                result.add(query);
                break;
            }
        }
    }
    return result;
}
```

queries = \[ "word ", "note ", "ants ", "wood "\], dictionary = \[ "wood ", "joke ", "moat "\]

["equal ", "eagle ", "apple ", "addle ", "heap ", "eelp ", "pale ", "elk "]
["equol ", "eaglq ", "applw ", "addlw ", "hepq ", "eelpq ", "pqlw ", "elko "]

["word", "note", "ants", "wood"]
["wood", "joke", "moat"]

["flood ", "goat ", "tree ", "apple ", "book ", "keep ", "test ", "gas "]
["flopd ", "goos ", "trea ", "applb ", "booke ", "kepe ", "testa ", "gass "]

["match ", "catch ", "chart ", "scatter ", "hart ", "bat ", "mat ", "cat "]
["march ", "cath ", "chat ", "scater ", "harte ", "bate ", "matt ", "catt "]

["hello ", "world ", "IDictionary ", "coding ", "play ", "stay ", "soup ", "losed "]
["world ", "word ", "dict ", "code ", "pla ", "stas ", "soop ", "losed "]

[ "word ", "note ", "ants ", "wood "]
[ "wood ", "joke ", "moat "]

flood goat tree apple book keep test gas

equal eagle apple addle heap eelp pale elk

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

int countDifferences(const std::string& a, const std::string& b) {
    int diff = 0;
    for (int i = 0; i < a.size(); ++i) {
        if (a[i] != b[i]) {
            ++diff;
        }
    }
    return diff;
}

std::vector<std::string> findMatchingWords(const std::vector<std::string>& queries, const std::vector<std::string>& dictionary) {
    std::vector<std::string> result;
    for (const std::string& query : queries) {
        for (const std::string& dictWord : dictionary) {
            if (countDifferences(query, dictWord) <= 2) {
                result.push_back(query);
                break;
            }
        }
    }
    return result;
}
```


```cpp
int minSeededValue(vector<int> &nums, int space) {
    unordered_map<int, int> count;
    for (int num : nums) {
        count[num % space]++;
    }
    return max_element(count.begin(), count.end(), [](const auto &a, const auto &b) {
        return a.second < b.second || (a.second == b.second && a.first > b.first);
    })->first;
}
```

```python
def minSeededValue(nums, space):
    count = {}
    for num in nums:
        count[num % space] = count.get(num % space, 0) + 1
    return max(count, key=lambda x: (count[x], -x))
```


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

vector<int> findSecondGreater(const vector<int>& nums) {
    int n = nums.size();
    vector<int> answer(n, -1);
    for (int i = 0; i < n; i++) {
        for (int j = i + 1, k = -1; j < n; j++) {
            if (nums[j] > nums[i]) {
                if (k == -1) {
                    k = j;
                } else {
                    answer[i] = nums[j];
                    break;
                }
            }
        }
    }
    return answer;
}
```

```python
def find_second_greater(nums):
    n = len(nums)
    answer = [-1] * n
    for i in range(n):
        k = -1
        for j in range(i + 1, n):
            if nums[j] > nums[i]:
                if k == -1:
                    k = j
                else:
                    answer[i] = nums[j]
                    break
    return answer
```


```python
def average_even_divisible_by_three(nums):
    total = 0
    count = 0
    for num in nums:
        if num % 2 == 0 and num % 3 == 0:
            total += num
            count += 1
    return total // count if count > 0 else 0
```

```cpp
int averageEvenDivisibleByThree(const std::vector<int>& nums) {
    int sum = 0;
    int count = 0;
    for (int num : nums) {
        if (num % 2 == 0 && num % 3 == 0) {
            sum += num;
            count++;
        }
    }
    return count == 0 ? 0 : sum / count;
}
```


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

std::vector<std::vector<std::string>> highestPopularity(std::vector<std::string>& creators, std::vector<std::string>& ids, std::vector<int>& views) {
    std::unordered_map<std::string, int> popularity;
    std::unordered_map<std::string, std::pair<std::string, int>> most_viewed;
    for(int i = 0; i < creators.size(); i++) {
        popularity[creators[i]] += views[i];
        if (!most_viewed.count(creators[i]) || views[i] > most_viewed[creators[i]].second
            || (views[i] == most_viewed[creators[i]].second && ids[i] < most_viewed[creators[i]].first))
        {
            most_viewed[creators[i]] = {ids[i], views[i]};
        }
    }

    int max_popularity = 0;
    for(auto& [creator, popular] : popularity) {
        max_popularity = std::max(max_popularity, popular);
    }

    std::vector<std::vector<std::string>> result;
    for(auto& [creator, popular] : popularity) {
        if (popular == max_popularity) {
            result.push_back({creator, most_viewed[creator].first});
        }
    }
    return result;
}
```

creators = \[ "alice ", "bob ", "alice ", "chris "\], ids = \[ "one ", "two ", "three ", "four "\], views = \[5,10,5,4\]

```python
from collections import defaultdict

def highest_popularity(creators, ids, views):
    popularity = defaultdict(int)
    most_viewed = {}

    for i in range(len(creators)):
        popularity[creators[i]] += views[i]
        if creators[i] not in most_viewed or views[i] > most_viewed[creators[i]][1] or (views[i] == most_viewed[creators[i]][1] and ids[i] < most_viewed[creators[i]][0]):
            most_viewed[creators[i]] = (ids[i], views[i])

    max_popularity = max(popularity.values())

    return [[creator, most_viewed[creator][0]] for creator, pop in popularity.items() if pop == max_popularity]
```


```python
def digit_sum(n):
    return sum(int(digit) for digit in str(n))

def minimum_beautiful(n, target):
    x = 0
    while digit_sum(n + x) > target:
        x += 1
    return x
```

```java
public int digitSum(int n) {
    int sum = 0;
    while (n > 0) {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}

public int minimumBeautiful(int n, int target) {
    int x = 0;
    while (digitSum(n + x) > target) {
        ++x;
    }
    return x;
}
```


```cpp
// Definition for a binary tree node.
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    vector<int> removeSubtrees(TreeNode* root, vector<int>& queries) {
        vector<int> answer(queries.size());

        for (int i = 0; i < queries.size(); ++i) {
            removeSubtree(root, queries[i]);
            answer[i] = findHeight(root);
        }

        return answer;
    }

    void removeSubtree(TreeNode* node, int val) {
        if (node == nullptr) return;

        if (node->left && node->left->val == val)
            node->left = nullptr;
        else
            removeSubtree(node->left, val);

        if (node->right && node->right->val == val)
            node->right = nullptr;
        else
            removeSubtree(node->right, val);
    }

    int findHeight(TreeNode* node) {
        if (node == nullptr) return -1;

        return 1 + max(findHeight(node->left), findHeight(node->right));
    }
};
```

root = \[1,3,4,2,null,6,5,null,null,null,null,null,7\], queries = \[4\]

```python
# Definition for a binary tree node.
class TreeNode:
    def __init__(self, x: int):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def removeSubtrees(self, root: TreeNode, queries: List[int]) -> List[int]:
        def removeSubtree(node: TreeNode, val: int):
            if not node: return

            if node.left and node.left.val == val:
                node.left = None
            else:
                removeSubtree(node.left, val)

            if node.right and node.right.val == val:
                node.right = None
            else:
                removeSubtree(node.right, val)

        def findHeight(node: TreeNode) -> int:
            if not node: return -1

            return 1 + max(findHeight(node.left), findHeight(node.right))

        answer = []
        for query in queries:
            removeSubtree(root, query)
            answer.append(findHeight(root))

        return answer
```


```python
def min_operations(nums):
    n = len(nums)
    idx0 = -1

    for i in range(n):
        if nums[i] == 0:
            idx0 = i
            break

    cnt1 = 0
    cnt2 = 0

    for i in range(1, n):
        if abs(nums[i] - nums[i - 1]) != 1:
            cnt1 += abs(nums[i] - nums[i - 1]) - 1

    for i in range(idx0 + 1, n):
        if nums[i] < nums[i - 1]:
            cnt2 += 1

    return min(cnt1, cnt2)
```

```cpp
int min_operations(vector<int>& nums) {
    int n = nums.size();
    int idx0 = -1;

    for(int i = 0; i < n; i++) {
        if(nums[i] == 0) {
            idx0 = i;
            break;
        }
    }

    int cnt1 = 0, cnt2 = 0;

    for(int i = 1; i < n; i++) {
        if(abs(nums[i] - nums[i - 1]) != 1) {
            cnt1 += abs(nums[i] - nums[i - 1]) - 1;
        }
    }

    for(int i = idx0 + 1; i < n; i++) {
        if(nums[i] < nums[i - 1]) {
            cnt2++;
        }
    }

    return min(cnt1, cnt2);
}
```


```python
def performOps(nums):
    n = len(nums)
    for i in range(n - 1):
        if nums[i] == nums[i + 1]:
            nums[i] *= 2
            nums[i + 1] = 0
    nonZeroIndex = 0
    for i in range(n):
        if nums[i] != 0:
            nums[nonZeroIndex] = nums[i]
            nonZeroIndex += 1
    while(nonZeroIndex < n):
        nums[nonZeroIndex] = 0
        nonZeroIndex += 1
    return nums
```

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

vector<int> performOps(vector<int>& nums) {
    int n = nums.size();
    for (int i = 0; i < n - 1; ++i) {
        if (nums[i] == nums[i + 1]) {
            nums[i] *= 2;
            nums[i + 1] = 0;
        }
    }
    int nonZeroIndex = 0;
    for (int i = 0; i < n; ++i) {
        if (nums[i] != 0) {
            nums[nonZeroIndex++] = nums[i];
        }
    }
    while (nonZeroIndex < n) {
        nums[nonZeroIndex++] = 0;
    }
    return nums;
}
```


```python
def hireWorkers(costs, k, candidates):
    n = len(costs)
    workers = sorted([(cost, i) for i, cost in enumerate(costs)])

    cost = 0
    for i in range(k):
        if min(workers[i][1], n - workers[i][1] - 1) < candidates:
            cost += workers[i][0]

    return cost
```

```cpp
int hireWorkers(vector<int>& costs, int k, int candidates) {
    int n = costs.size();
    vector<pair<int, int>> workers;
    for (int i = 0; i < n; ++i)
        workers.emplace_back(costs[i], i);
    sort(workers.begin(), workers.end());

    int cost = 0;
    for (int i = 0; i < k; ++i) {
        if (min(workers[i].second, n - workers[i].second - 1) < candidates)
            cost += workers[i].first;
    }
    return cost;
}
```


```python
def min_total_distance(robot: List[int], factory: List[List[int]]) -> int:
    robot.sort()
    factory.sort()

    res = 0
    idx = 0
    for f_pos, f_limit in factory:
        while f_limit > 0 and idx < len(robot):
            res += abs(f_pos - robot[idx])
            idx += 1
            f_limit -= 1

    return res
```

```cpp
int minTotalDistance(vector<int>& robot, vector<vector<int>>& factory) {
    sort(robot.begin(), robot.end());
    sort(factory.begin(), factory.end());

    int res = 0, idx = 0;
    for (const auto& f : factory) {
        int limit = f[1];
        while (limit-- > 0 && idx < robot.size()) {
            res += abs(f[0] - robot[idx]);
            idx++;
        }
    }

    return res;
}
```


```cpp
#include <numeric>
int min_valid_subarrays(vector<int>& nums) {
    int count = 0;
    for (int i = 0; i < nums.size(); i++) {
        while (i < nums.size() && std::gcd(nums[i], nums.back()) == 1) {
            i++;
        }
        if (i < nums.size()) {
            count++;
            nums.pop_back();
        }
    }
    return count > 0 ? count : -1;
}
```

```java
public int minValidSubarrays(int[] nums) {
    int count = 0;
    while(nums.length > 0) {
        int i;
        for (i = 0; i < nums.length; i++) {
            if (gcd(nums[i], nums[nums.length - 1]) > 1) {
                break;
            }
        }
        if (i == nums.length) {
            nums = Arrays.copyOf(nums, nums.length - 1);
            count++;
        } else {
            break;
        }
    }
    return (count > 0) ? count : -1;
}

private int gcd(int a, int b) {
    while (b != 0) {
        int temp = a % b;
        a = b;
        b = temp;
    }
    return a;
}
```


```python
def distinctAverages(nums):
    averages = set()
    nums.sort()
    n = len(nums)
    for i in range(n // 2):
        averages.add((nums[i] + nums[n - 1 - i]) / 2.0)
    return len(averages)
```

```cpp
int distinctAverages(vector<int>& nums) {
    set<double> averages;
    sort(nums.begin(), nums.end());
    int n = nums.size();
    for (int i = 0; i < n / 2; i++) {
        averages.insert((nums[i] + nums[n - 1 - i]) / 2.0);
    }
    return averages.size();
}
```


```java
public double[] convertTemperature(double celsius) {
    double kelvin = celsius + 273.15;
    double fahrenheit = celsius * 1.80 + 32.00;
    return new double[]{kelvin, fahrenheit};
}
```

```python
def convert_temperature(celsius):
    kelvin = celsius + 273.15
    fahrenheit = celsius * 1.8 + 32
    return [kelvin, fahrenheit]
```


```python
def count_lcm_subarrays(nums: List[int], k: int) -> int:
    def lcm(a, b):
        temp = a
        while temp % b != 0:
            temp += a
        return temp

    count = 0
    for i in range(len(nums)):
        curr_lcm = nums[i]
        for j in range(i, len(nums)):
            curr_lcm = lcm(curr_lcm, nums[j])
            if curr_lcm == k:
                count += 1

    return count
```

```java
public int countLCMSubarrays(int[] nums, int k) {
    int count = 0;
    for (int i = 0; i < nums.length; i++) {
        int curr_lcm = nums[i];
        for (int j = i; j < nums.length; j++) {
            curr_lcm = lcm(curr_lcm, nums[j]);
            if (curr_lcm == k) {
                count++;
            }
        }
    }
    return count;
}

private int lcm(int a, int b) {
    int temp = a;
    while ((temp % b) != 0) {
        temp += a;
    }
    return temp;
}
```


```java
import java.util.*;

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    public int minSwaps(TreeNode root) {
        int count = 0;
        Queue<Pair<TreeNode, Integer>> que = new LinkedList<>();
        que.add(new Pair<>(root, 0));

        List<Integer> levelVals = new ArrayList<>();
        int prevDepth = -1;

        while (!que.isEmpty()) {
            Pair<TreeNode, Integer> curr = que.remove();
            TreeNode node = curr.getKey();
            int depth = curr.getValue();

            if (prevDepth != depth) {
                Collections.sort(levelVals);
                for (int i = 1; i < levelVals.size(); ++i) {
                    count += Math.abs(levelVals.get(i) - levelVals.get(i-1)) - 1;
                }
                prevDepth = depth;
                levelVals.clear();
            }
            levelVals.add(node.val);

            if (node.left != null) que.add(new Pair<>(node.left, depth + 1));
            if (node.right != null) que.add(new Pair<>(node.right, depth + 1));
        }

        Collections.sort(levelVals);
        for (int i = 1; i < levelVals.size(); ++i) {
            count += Math.abs(levelVals.get(i) - levelVals.get(i-1)) - 1;
        }

        return count;
    }
}
```

```python
from collections import deque

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

def minSwaps(root: TreeNode) -> int:
    count = 0
    que = deque([(root, 0)])

    level_vals = []
    prev_depth = -1

    while que:
        node, depth = que.popleft()

        if prev_depth != depth:
            level_vals.sort()
            for i in range(1, len(level_vals)):
                count += abs(level_vals[i] - level_vals[i-1]) - 1
            prev_depth = depth
            level_vals.clear()
        level_vals.append(node.val)

        if node.left:
            que.append((node.left, depth + 1))
        if node.right:
            que.append((node.right, depth + 1))

    level_vals.sort()
    for i in range(1, len(level_vals)):
        count += abs(level_vals[i] - level_vals[i-1]) - 1

    return count
```


```java
public int maxPalindromesSubstrings(String s, int k) {
    int n = s.length();
    if (n < k) {
        return 0;
    }
    int count = 0;
    boolean[][] dp = new boolean[n][n];
    for (int i = n - 1; i >= 0; i--) {
        for (int j = i; j < n; j++) {
            if (i == j) {
                dp[i][j] = true;
            } else if (s.charAt(i) == s.charAt(j)) {
                dp[i][j] = i + 1 > j - 1 || dp[i + 1][j - 1];
            } else {
                dp[i][j] = false;
            }
            if (j - i + 1 >= k && dp[i][j]) {
                count++;
                i = j;
                break;
            }
        }
    }
    return count;
}
```

```python
def maxPalindromesSubstrings(s, k):
    n = len(s)
    if n < k:
        return 0
    count = 0
    dp = [[False] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(i, n):
            if i == j:
                dp[i][j] = True
            elif s[i] == s[j]:
                dp[i][j] = i + 1 > j - 1 or dp[i + 1][j - 1]
            else:
                dp[i][j] = False
            if j - i + 1 >= k and dp[i][j]:
                count += 1
                i = j
                break
    return count
```


```java
public int countTriplets(int[] nums) {
    int count = 0;
    int n = nums.length;

    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n; j++) {
            for(int k = j + 1; k < n; k++) {
                if(nums[i] != nums[j] && nums[i] != nums[k] && nums[j] != nums[k]) {
                    count++;
                }
            }
        }
    }

    return count;
}
```

```cpp
int countTriplets(vector<int>& nums) {
    int count = 0;
    int n = nums.size();

    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n; j++) {
            for(int k = j + 1; k < n; k++) {
                if(nums[i] != nums[j] && nums[i] != nums[k] && nums[j] != nums[k]) {
                    count++;
                }
            }
        }
    }

    return count;
}
```


```cpp
#include<vector>

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

std::vector<std::vector<int>> findMinMax(TreeNode* root, std::vector<int>& queries) {
    if (!root) {
        return {};
    }

    std::vector<std::vector<int>> ans(queries.size(), std::vector<int>{-1, -1});
    for (size_t i = 0; i < queries.size(); i++) {
        TreeNode* node = root;
        int query = queries[i];
        while (node) {
            if (node->val < query) {
                ans[i][0] = node->val;
                node = node->right;
            } else {
                ans[i][1] = node->val;
                if (node->val == query) {
                    ans[i][0] = query;
                    break;
                }
                node = node->left;
            }
        }
    }
    return ans;
}
```

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

def findMinMax(root, queries):
    if not root:
        return []

    ans = [[-1, -1] for _ in range(len(queries))]
    for i in range(len(queries)):
        node = root
        query = queries[i]
        while node:
            if node.val < query:
                ans[i][0] = node.val
                node = node.right
            else:
                ans[i][1] = node.val
                if node.val == query:
                    ans[i][0] = query
                    break
                node = node.left
    return ans
```


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

int minFuel(std::vector<std::vector<int>>& roads, int seats) {
    int n = roads.size() + 1;
    std::vector<std::vector<int>> graph(n);
    for (auto& road : roads) {
        graph[road[0]].push_back(road[1]);
        graph[road[1]].push_back(road[0]);
    }

    std::vector<int> distance(n, -1);
    std::queue<int> q;
    q.push(0);
    distance[0] = 0;

    while (!q.empty()) {
        int city = q.front();
        q.pop();
        for (int neighbor : graph[city]) {
            if (distance[neighbor] == -1) {
                distance[neighbor] = distance[city] + 1;
                q.push(neighbor);
            }
        }
    }

    int totalFuel = 0;
    for (int city = 1; city < n; city++) {
        totalFuel += (distance[city] - 1) / (seats - 1) + 1;
    }
    return totalFuel;
}
```

```python
from collections import defaultdict, deque

def min_fuel(roads, seats):
    n = len(roads) + 1
    graph = defaultdict(list)
    for road in roads:
        graph[road[0]].append(road[1])
        graph[road[1]].append(road[0])

    distance = [-1] * n
    q = deque([0])
    distance[0] = 0

    while q:
        city = q.popleft()
        for neighbor in graph[city]:
            if distance[neighbor] == -1:
                distance[neighbor] = distance[city] + 1
                q.append(neighbor)

    total_fuel = 0
    for city in range(1, n):
        total_fuel += (distance[city] - 1) // (seats - 1) + 1
    return total_fuel
```


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

using namespace std;

int numBeautifulPartitions(const string& s, int k, int minLength) {
    const int MOD = 1e9 + 7;
    unordered_set<char> primes = {'2', '3', '5', '7'};
    int n = s.length();
    vector<vector<int>> dp(n + 1, vector<int>(k + 1, 0));
    dp[0][0] = 1;

    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= k; ++j) {
            for (int l = minLength; l <= i && i - l >= j - 1; ++l) {
                if (primes.count(s[i - l]) && !primes.count(s[i - 1])) {
                    dp[i][j] += dp[i - l][j - 1];
                    if (dp[i][j] >= MOD) dp[i][j] -= MOD;
                }
            }
        }
    }

    return dp[n][k];
}
```

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

public class Solution {
    public int numBeautifulPartitions(String s, int k, int minLength) {
        final int MOD = 1000000007;
        Set<Character> primes = new HashSet<>();
        primes.add('2');
        primes.add('3');
        primes.add('5');
        primes.add('7');

        int n = s.length();
        int[][] dp = new int[n + 1][k + 1];
        dp[0][0] = 1;

        for (int i = 1; i <= n; ++i) {
            for (int j = 1; j <= k; ++j) {
                for (int l = minLength; l <= i && i - l >= j - 1; ++l) {
                    if (primes.contains(s.charAt(i - l)) && !primes.contains(s.charAt(i - 1))) {
                        dp[i][j] += dp[i - l][j - 1];
                        if (dp[i][j] >= MOD) dp[i][j] -= MOD;
                    }
                }
            }
        }

        return dp[n][k];
    }
}
```


```java
import java.util.*;

public int maxXorSubtree(int n, int[][] edges, int[] values) {
    List<List<Integer>> tree = new ArrayList<>();

    for (int i = 0; i < n; i++) {
        tree.add(new ArrayList<>());
    }

    for (int[] edge : edges) {
        tree.get(edge[0]).add(edge[1]);
        tree.get(edge[1]).add(edge[0]);
    }

    int[] firstMax = new int[]{0};
    int rootSum = dfs(0, -1, tree, values, firstMax);

    return rootSum ^ firstMax[0];
}

private int dfs(int node, int parent, List<List<Integer>> tree, int[] values, int[] firstMax) {
    int currentSum = values[node];

    for (int child : tree.get(node)) {
        if (child != parent) {
            currentSum ^= dfs(child, node, tree, values, firstMax);
        }
    }

    firstMax[0] = Math.max(firstMax[0], currentSum);

    return currentSum;
}
```

```python
from collections import defaultdict

def maxXorSubtree(n, edges, values):
    tree = defaultdict(list)

    for edge in edges:
        tree[edge[0]].append(edge[1])
        tree[edge[1]].append(edge[0])

    first_max = [0]
    root_sum = dfs(0, -1, tree, values, first_max)

    return root_sum ^ first_max[0]

def dfs(node, parent, tree, values, first_max):
    current_sum = values[node]

    for child in tree[node]:
        if child != parent:
            current_sum ^= dfs(child, node, tree, values, first_max)

    first_max[0] = max(first_max[0], current_sum)

    return current_sum
```


```cpp
int min_cuts(int n) {
    if (n % 2 == 0)
        return n / 2;
    else
        return n;
}
```

```python
def min_cuts(n):
    if n % 2 == 0:
        return n // 2
    else:
        return n
```


```cpp
vector<vector<int>> createDifferenceMatrix(vector<vector<int>>& grid) {
    int m = grid.size(), n = grid[0].size();
    vector<int> onesRow(m, 0), onesCol(n, 0);
    vector<vector<int>> diff(m, vector<int>(n));

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            onesRow[i] += grid[i][j];
            onesCol[j] += grid[i][j];
        }
    }

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            diff[i][j] = onesRow[i] + onesCol[j] - (n - onesRow[i]) - (m - onesCol[j]);
        }
    }

    return diff;
}
```

```python
def create_difference_matrix(grid):
    m, n = len(grid), len(grid[0])
    ones_row, ones_col = [0] * m, [0] * n
    diff = [[0] * n for _ in range(m)]

    for i in range(m):
        for j in range(n):
            ones_row[i] += grid[i][j]
            ones_col[j] += grid[i][j]

    for i in range(m):
        for j in range(n):
            diff[i][j] = ones_row[i] + ones_col[j] - (n - ones_row[i]) - (m - ones_col[j])

    return diff
```


```python
def find_pivot(n: int) -> int:
    total = n * (n + 1) // 2
    left_sum = 0
    for x in range(1, n + 1):
        left_sum += x
        if 2 * left_sum == total:
            return x
    return -1
```

```java
public int findPivot(int n) {
    int sum = n * (n + 1) / 2;
    int left_sum = 0;
    for (int x = 1; x <= n; x++) {
        left_sum += x;
        if (left_sum * 2 == sum) {
            return x;
        }
    }
    return -1;
}
```


```python
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def removeNodes(head):
    if not head: return None
    maxNode = head
    currentNode = head
    prevNode = None

    while currentNode and currentNode.next:
        if currentNode.next.val > maxNode.val:
            if prevNode: prevNode.next = currentNode.next
            else: head = currentNode.next
            maxNode = currentNode.next
        else:
            prevNode = currentNode
        currentNode = currentNode.next
    maxNode.next = removeNodes(maxNode.next)
    return head
```

```cpp
class ListNode {
public:
    int val;
    ListNode* next;
};

ListNode* removeNodes(ListNode* head) {
    if (!head) return nullptr;
    ListNode* maxNode = head;
    ListNode* currentNode = head;
    ListNode* prevNode = nullptr;

    while (currentNode && currentNode->next) {
        if (currentNode->next->val > maxNode->val) {
            if (prevNode) prevNode->next = currentNode->next;
            else head = currentNode->next;
            maxNode = currentNode->next;
        } else {
            prevNode = currentNode;
        }
        currentNode = currentNode->next;
    }
    maxNode->next = removeNodes(maxNode->next);
    return head;
}
```


```java
int countSubarraysWithMedian(int[] nums, int k) {
    int ans = 0;
    for (int left = 0; left < nums.length; ++left) {
        int count = 0;
        List<Integer> subarray = new ArrayList<>();
        for (int right = left; right < nums.length; ++right) {
            count += (nums[right] == k) ? 1 : 0;
            int index = Collections.binarySearch(subarray, nums[right]);
            index = index >= 0 ? index : ~index;
            subarray.add(index, nums[right]);
            if (subarray.size() % 2 == 1 && subarray.get(subarray.size() / 2) == k) {
                ans += count;
            }
        }
    }
    return ans;
}
```

```cpp
int countSubarraysWithMedian(std::vector<int>& nums, int k) {
    int ans = 0;
    for (int left = 0; left < nums.size(); ++left) {
        int count = 0;
        std::vector<int> subarray;
        for (int right = left; right < nums.size(); ++right) {
            count += (nums[right] == k);
            subarray.insert(lower_bound(subarray.begin(), subarray.end(), nums[right]), nums[right]);
            if ((subarray.size() % 2 == 1) && (subarray[subarray.size() / 2] == k)) {
                ans += count;
            }
        }
    }
    return ans;
}
```


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

int maximumChemistry(vector<int>& skill) {
    int total_sum = 0;
    for (int s : skill) {
        total_sum += s;
    }
    int target_sum = total_sum / 2;
    if (total_sum % 2 == 1) return -1;

    unordered_map<int, int> dp;
    dp[0] = 1;
    int max_chemistry = 0;

    for (int s : skill) {
        for (int i = target_sum - s; i >= 0; i--) {
            if (dp[i]) {
                dp[i + s] += dp[i];
                if (i + s == target_sum) {
                    max_chemistry += dp[i] * s;
                }
            }
        }
    }

    return (max_chemistry > 0) ? max_chemistry : -1;
}
```

```python
def maximumChemistry(skill):
    total_sum = sum(skill)
    target_sum = total_sum // 2
    if total_sum % 2 == 1:
        return -1

    dp = {0: 1}
    max_chemistry = 0

    for s in skill:
        for i in range(target_sum - s, -1, -1):
            if i in dp:
                dp[i + s] = dp.get(i + s, 0) + dp[i]
                if i + s == target_sum:
                    max_chemistry += dp[i] * s

    return max_chemistry if max_chemistry > 0 else -1
```


```python
from heapq import heappush, heappop
from collections import defaultdict

def minimumScore(n, roads):
    adj = defaultdict(list)
    for road in roads:
        adj[road[0]].append((road[1], road[2]))
        adj[road[1]].append((road[0], road[2]))

    INF = int(1e9)
    pq = [(0, 1)]

    minDist = [INF] * (n + 1)
    while pq:
        curDist, curCity = heappop(pq)

        if curCity == n:
            return curDist

        if curDist < minDist[curCity]:
            minDist[curCity] = curDist
            for nextCity, nextDist in adj[curCity]:
                candidate_dist = max(curDist, nextDist)
                if candidate_dist < minDist[nextCity]:
                    heappush(pq, (candidate_dist, nextCity))

    return -1
```

```cpp
int minimumScore(int n, vector<vector<int>>& roads) {
    vector<vector<pair<int, int>>> adj(n + 1);
    for (const auto& road : roads) {
        adj[road[0]].push_back({road[1], road[2]});
        adj[road[1]].push_back({road[0], road[2]});
    }

    const int INF = 1e9;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
    pq.push({0, 1});

    vector<int> minDist(n + 1, INF);
    while (!pq.empty()) {
        int curCity = pq.top().second;
        int curDist = pq.top().first;
        pq.pop();

        if (curCity == n) {
            return curDist;
        }

        if (curDist < minDist[curCity]) {
            minDist[curCity] = curDist;
            for (const auto& neighbor : adj[curCity]) {
                int nextCity = neighbor.first;
                int nextDist = max(curDist, neighbor.second);
                if (nextDist < minDist[nextCity]) {
                    pq.push({nextDist, nextCity});
                }
            }
        }
    }

    return -1;
}
```


```python
from collections import defaultdict, deque

def maxGroups(n, edges):
    graph = defaultdict(list)
    color = [0] * (n + 1)

    for edge in edges:
        graph[edge[0]].append(edge[1])
        graph[edge[1]].append(edge[0])

    max_group = 0
    for i in range(1, n + 1):
        if color[i] == 0:
            q = deque([i])
            color[i] = 1
            while q:
                node = q.popleft()
                max_group = max(max_group, color[node])
                for neighbor in graph[node]:
                    if color[neighbor] == 0:
                        color[neighbor] = color[node] + 1
                        q.append(neighbor)
                    elif color[neighbor] == color[node]:
                        return -1

    return max_group
```

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

int maxGroups(int n, std::vector<std::vector<int>>& edges) {
    std::vector<std::vector<int>> graph(n + 1);
    std::vector<int> color(n + 1, 0);

    for (auto& edge : edges) {
        graph[edge[0]].push_back(edge[1]);
        graph[edge[1]].push_back(edge[0]);
    }

    int max_group = 0;
    for (int i = 1; i <= n; ++i) {
        if (color[i] == 0) {
            std::queue<int> q;
            q.push(i);
            color[i] = 1;
            while (!q.empty()) {
                int node = q.front();
                q.pop();
                max_group = std::max(max_group, color[node]);
                for (int neighbor : graph[node]) {
                    if (color[neighbor] == 0) {
                        color[neighbor] = color[node] + 1;
                        q.push(neighbor);
                    } else if (color[neighbor] == color[node]) {
                        return -1;
                    }
                }
            }
        }
    }
    return max_group;
}
```


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

int maxValue(std::vector<std::string>& strs) {
    int max_value = 0;
    for (const std::string& str : strs) {
        int value;
        if (str.find_first_not_of("0123456789") == std::string::npos) {
            value = std::stoi(str);
        } else {
            value = static_cast<int>(str.length());
        }
        max_value = std::max(max_value, value);
    }
    return max_value;
}
```

coding programming algorithm data structure

```java
import java.util.List;

public int maxValue(List<String> strs) {
    int maxValue = 0;
    for (String str : strs) {
        int value;
        if (str.chars().allMatch(Character::isDigit)) {
            value = Integer.parseInt(str);
        } else {
            value = str.length();
        }
        maxValue = Math.max(maxValue, value);
    }
    return maxValue;
}
```


```java
import java.util.*;

public int maxStarSum(int[] vals, int[][] edges, int k) {
    List<Integer>[] adj = new ArrayList[vals.length];
    for (int i = 0; i < vals.length; i++) {
        adj[i] = new ArrayList<Integer>();
    }

    for (int[] edge : edges) {
        adj[edge[0]].add(vals[edge[1]]);
        adj[edge[1]].add(vals[edge[0]]);
    }

    int ans = Integer.MIN_VALUE;
    for (int i = 0; i < vals.length; i++) {
        Collections.sort(adj[i], Collections.reverseOrder());
        int sum = vals[i];
        for (int j = 0; j < k && j < adj[i].size(); j++) {
            sum += adj[i].get(j);
        }
        ans = Math.max(ans, sum);
    }

    return ans;
}
```

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

int maxStarSum(const vector<int>& vals, const vector<vector<int>>& edges, int k) {
    vector<int> adj[100000];
    int ans = -1e9;

    for (const vector<int>& edge : edges) {
        adj[edge[0]].push_back(vals[edge[1]]);
        adj[edge[1]].push_back(vals[edge[0]]);
    }

    for (int i = 0; i < vals.size(); i++) {
        sort(adj[i].rbegin(), adj[i].rend());
        int sum = vals[i];
        for (int j = 0; j < k && j < adj[i].size(); j++) {
            sum += adj[i][j];
        }
        ans = max(ans, sum);
    }

    return ans;
}
```


```java
public int minimumPathCost(int[] stones) {
    int n = stones.length;
    int max_cost = stones[n-1];
    for(int i = 1; i < n-1; ++i){
        max_cost = Math.min(max_cost, Math.max(stones[i], stones[n-1]-stones[i]));
    }
    return max_cost;
}
```

```python
def minimum_path_cost(stones):
    n = len(stones)
    max_cost = stones[n-1]
    for i in range(1, n-1):
        max_cost = min(max_cost, max(stones[i], stones[n-1]-stones[i]))
    return max_cost
```


```java
public int minCost(int[] nums1, int[] nums2) {
    Map<Integer, List<Integer>> valueToIndices = new HashMap<>();
    for (int i = 0; i < nums1.length; ++i) {
        valueToIndices.putIfAbsent(nums1[i], new ArrayList<>());
        valueToIndices.get(nums1[i]).add(i);
    }

    int result = 0;
    for (int val : nums2) {
        List<Integer> indices = valueToIndices.get(val);
        if (indices == null || indices.isEmpty()) return -1;
        result += indices.get(indices.size() - 1);
        indices.remove(indices.size() - 1);
    }

    return result;
}
```

```python
def min_cost(nums1: List[int], nums2: List[int]) -> int:
    value_to_indices = {}
    for i, val in enumerate(nums1):
        value_to_indices.setdefault(val, []).append(i)

    result = 0
    for val in nums2:
        if not value_to_indices[val]:
            return -1
        result += value_to_indices[val].pop()

    return result
```


```java
import java.util.*;

public List<Integer> maxPoints(int[][] grid, int[] queries) {
    int m = grid.length;
    int n = grid[0].length;
    int[] dx = {-1, 0, 1, 0};
    int[] dy = {0, 1, 0, -1};
    List<Integer> result = new ArrayList<>();

    for (int query : queries) {
        int points = 0;
        Set<String> visited = new HashSet<>();
        Stack<int[]> stack = new Stack<>();
        stack.push(new int[]{0, 0});

        while (!stack.isEmpty()) {
            int[] cur = stack.pop();
            int x = cur[0], y = cur[1];
            String coordStr = x + "," + y;

            if (!visited.contains(coordStr) && grid[x][y] < query) {
                visited.add(coordStr);
                points++;
                for (int i = 0; i < 4; i++) {
                    int nx = x + dx[i], ny = y + dy[i];
                    if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                        stack.push(new int[]{nx, ny});
                    }
                }
            }
        }
        result.add(points);
    }
    return result;
}
```

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

vector<int> traverseMatrix(vector<vector<int>>& grid, const vector<int>& queries, int m, int n) {
    vector<int> dx = {-1, 0, 1, 0};
    vector<int> dy = {0, 1, 0, -1};
    vector<int> answer(queries.size(), 0);

    for (int k = 0; k < queries.size(); ++k) {
        int q = queries[k];
        int points = 0;
        set<pair<int, int>> visited;

        function<void(int, int)> dfs = [&](int x, int y) {
            if (visited.find({x, y}) == visited.end() && grid[x][y] < q) {
                visited.insert({x, y});
                points++;
                for (int i = 0; i < 4; ++i) {
                    int nx = x + dx[i], ny = y + dy[i];
                    if (nx >= 0 && nx < m && ny >= 0 && ny < n) {
                        dfs(nx, ny);
                    }
                }
            }
        };

        dfs(0, 0);
        answer[k] = points;
    }

    return answer;
}

vector<int> maxPoints(vector<vector<int>>& grid, vector<int>& queries) {
    int m = grid.size();
    int n = grid[0].size();
    return traverseMatrix(grid, queries, m, n);
}
```


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

int count_similar_pairs(std::vector<std::string>& words) {
    int count = 0;
    for (int i = 0; i < words.size(); ++i) {
        for (int j = i + 1; j < words.size(); ++j) {
            std::unordered_set<char> set1{words[i].begin(), words[i].end()};
            std::unordered_set<char> set2{words[j].begin(), words[j].end()};
            if (set1 == set2) count++;
        }
    }
    return count;
}
```

words = \[ "aba ", "aabb ", "abcd ", "bac ", "aabc "\]

aabbcc dd eeff gg hhii jjkk llmm nnoo ppqq rrss ttuu vvww

abc def ghi jkl mno pqr stu vwxy z aa bb cc

```python
def count_similar_pairs(words):
    count = 0
    for i in range(len(words)):
        for j in range(i + 1, len(words)):
            set1 = set(words[i])
            set2 = set(words[j])
            if set1 == set2:
                count += 1
    return count
```


```cpp
int smallestFactorization(int n) {
    if (n <= 3)
        return n;
    int result = 0, factor = 1;
    for (int i = 2; i <= 5; ++i) {
        while (n % i == 0) {
            result += factor * i;
            factor *= 10;
            n /= i;
        }
    }
    return n == 1 ? result : n;
}
```

```python
def smallestFactorization(n):
    if n <= 3:
        return n
    result, factor = 0, 1
    for i in range(2, 6):
        while n % i == 0:
            result += factor * i
            factor *= 10
            n //= i
    return result if n == 1 else n
```


```java
import java.util.HashMap;

public boolean possibleDegreeEven(int n, int[][] edges) {
    HashMap<Integer, Integer> degrees = new HashMap<>();
    for (int[] edge : edges) {
        degrees.put(edge[0], degrees.getOrDefault(edge[0], 0) + 1);
        degrees.put(edge[1], degrees.getOrDefault(edge[1], 0) + 1);
    }

    int odd_degrees = 0;
    for (int i = 1; i <= n; i++) {
        if (degrees.getOrDefault(i, 0) % 2 != 0) odd_degrees++;
    }

    return (odd_degrees == 0 || odd_degrees == 2);
}
```

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

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

bool possibleDegreeEven(int n, vector<vector<int>>& edges) {
    vector<int> degrees(n + 1, 0);
    for (const auto& edge : edges) {
        degrees[edge[0]]++;
        degrees[edge[1]]++;
    }

    int odd_degrees = 0;
    for (int i = 1; i <= n; i++) {
        if (degrees[i] % 2 != 0) odd_degrees++;
    }

    return (odd_degrees == 0 || odd_degrees == 2);
}
```


```python
def length_of_cycle(n, queries):
    result = []
    for A, B in queries:
        depth_A, depth_B = 0, 0
        while A != B:
            if A < B:
                A, B = B, A
            A >>= 1
            depth_A += 1
        result.append(depth_A + depth_B)
    return result
```

```cpp
#include <vector>

std::vector<int> length_of_cycle(int n, const std::vector<std::vector<int>>& queries) {
    std::vector<int> result;
    for (const auto& query : queries) {
        int depth_A = 0, depth_B = 0, A = query[0], B = query[1];
        while (A != B) {
            if (A < B) std::swap(A, B);
            A >>= 1;
            depth_A++;
        }
        result.push_back(depth_A + depth_B);
    }
    return result;
}
```


```python
def isValidPath(grid, row, col, zeros, ones):
    if row < 0 or col < 0 or row >= len(grid) or col >= len(grid[0]):
        return False
    if grid[row][col] == 1:
        ones += 1
    else:
        zeros += 1
    if row == len(grid) - 1 and col == len(grid[0]) - 1:
        return zeros == ones
    return (isValidPath(grid, row + 1, col, zeros, ones)
            or isValidPath(grid, row, col + 1, zeros, ones))

def equalPath(grid):
    return isValidPath(grid, 0, 0, 0, 0)
```

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

```cpp
bool isValidPath(vector<vector<int>>& grid, int row, int col, int zeros, int ones) {
    if (row < 0 || col < 0 || row >= grid.size() || col >= grid[0].size()) {
        return false;
    }
    if (grid[row][col] == 1) {
        ones++;
    } else {
        zeros++;
    }
    if (row == grid.size() - 1 && col == grid[0].size() - 1) {
        return zeros == ones;
    }
    return isValidPath(grid, row + 1, col, zeros, ones) || isValidPath(grid, row, col + 1, zeros, ones);
}

bool equalPath(vector<vector<int>>& grid) {
    return isValidPath(grid, 0, 0, 0, 0);
}
```


```python
def max_captured_forts(forts):
    n = len(forts)
    max_capture = 0
    for i in range(n):
        if forts[i] == 1:
            for j in range(i+1, n):
                if forts[j] != -1:
                    capture = sum(1 for k in range(i+1, j) if forts[k] == 0)
                    if forts[j] == 1:
                        max_capture = max(max_capture, capture)
    return max_capture
```

```cpp
int maxCapturedForts(vector<int>& forts) {
    int n = forts.size();
    int maxCapture = 0;
    for(int i = 0; i < n; i++) {
        if(forts[i] == 1) {
            for(int j = i + 1; j < n; j++) {
                if(forts[j] != -1) {
                    int capture = 0;
                    for(int k = i + 1; k < j; k++) {
                        if(forts[k] == 0) capture++;
                    }
                    if(forts[j] == 1) maxCapture = max(maxCapture, capture);
                }
            }
        }
    }
    return maxCapture;
}
```