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

std::vector<int> top_k_students(const std::vector<std::string>& positive_feedback,
                                 const std::vector<std::string>& negative_feedback,
                                 const std::vector<std::string>& report,
                                 const std::vector<int>& student_id,
                                 int k) {
    std::unordered_map<int, int> points;
    for (size_t i = 0; i < report.size(); ++i) {
        int pos_count = 0, neg_count = 0;
        for (const auto& pos : positive_feedback) {
            size_t pos_index = report[i].find(pos);
            while (pos_index != std::string::npos) {
                ++pos_count;
                pos_index = report[i].find(pos, pos_index + pos.length());
            }
        }
        for (const auto& neg : negative_feedback) {
            size_t neg_index = report[i].find(neg);
            while (neg_index != std::string::npos) {
                ++neg_count;
                neg_index = report[i].find(neg, neg_index + neg.length());
            }
        }
        points[student_id[i]] += 3 * pos_count - neg_count;
    }

    std::vector<int> students(student_id.begin(), student_id.end());
    std::sort(students.begin(), students.end(), [&points](int a, int b) {
        return points[a] != points[b] ? points[a] > points[b] : a < b;
    });

    return std::vector<int>(students.begin(), students.begin() + k);
}
```

positive\_feedback = \[ "smart ", "brilliant ", "studious "\], negative\_feedback = \[ "not "\], report = \[ "this student is studious ", "the student is smart "\], student\_id = \[1,2\], k = 2

["outstanding", "proficient"]
[]
["student is outstanding", "another student is proficient"]
[30, 40]
1

[ "talented", "gifted", "bright" ]
[ "lazy" ]
[ "this student is lazy", "the student is talented" ]
[2,3]
2

[ "punctual", "honest", "reliable" ]
[ "arrogant" ]
[ "this student is arrogant", "the student is reliable" ]
[3,1]
2

[]
["careless", "absent"]
["student is careless", "the other is often absent"]
[50, 60]
2

["intelligent", "hardworking", "disciplined"]
["lazy", "inattentive"]
["this student is hardworking", "the student is intelligent but inattentive"]
[10, 20]
2

[ "good", "great", "excellent" ]
[ "bad" ]
[ "this student is good", "the student is bad" ]
[1,2]
1

[ "hardworking", "dedicated", "loyal" ]
[ "dishonest" ]
[ "this student is dishonest", "the student is loyal" ]
[1,2]
1

[ "smart ", "brilliant ", "studious "]
[ "not "]
[ "this student is studious ", "the student is smart "]
[1,2]
2

```python
def top_k_students(positive_feedback, negative_feedback, report, student_id, k):
    points = {}
    for i in range(len(report)):
        pos_count, neg_count = 0, 0
        for pos in positive_feedback:
            pos_index = report[i].find(pos)
            while pos_index != -1:
                pos_count += 1
                pos_index = report[i].find(pos, pos_index + len(pos))
        for neg in negative_feedback:
            neg_index = report[i].find(neg)
            while neg_index != -1:
                neg_count += 1
                neg_index = report[i].find(neg, neg_index + len(neg))

        points[student_id[i]] = points.get(student_id[i], 0) + 3 * pos_count - neg_count

    students = sorted(student_id, key=lambda x: (-points[x], x))
    return students[:k]
```


```java
public int minimumPossibleMax(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) {
    return (divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1;
}
```

divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3

```cpp
int minimumPossibleMax(int divisor1, int divisor2, int uniqueCnt1, int uniqueCnt2) {
    return (divisor1 - 1) * uniqueCnt1 + (divisor2 - 1) * uniqueCnt2 + 1;
}
```


```java
public int shortest_distance(String[] words, String target, int startIndex) {
    int n = words.length;
    int left = 0, right = 0, i = startIndex;
    while (true) {
        if (words[i].equals(target)) {
            return Math.min(left, right);
        }
        left++;
        right++;
        i = (i + 1) % n;
        if (left == n) {
            break;
        }
    }
    return -1;
}
```

words = \[ "hello ", "i ", "am ", "leetcode ", "hello "\], target =  "hello ", startIndex = 1

["hello", "i", "am", "leetcode", "hello"]
leetcode
1

["hello", "i", "am", "leetcode", "hello"]
leetcode
4

["hello", "i", "am", "leetcode", "hello"]
hello
0

["hello", "i", "am", "leetcode", "hello"]
leetcode
0

["hello", "i", "am", "leetcode", "hello"]
hello
2

["hello", "i", "am", "leetcode", "hello"]
i
2

["hello", "i", "am", "leetcode", "hello"]
am
4

["hello ", "i ", "am ", "leetcode ", "hello "]
hello
1

["hello", "i", "am", "leetcode", "hello"]
i
3

["hello", "i", "am", "leetcode", "hello"]
leetcode
2

["hello", "i", "am", "leetcode", "hello"]
hello
4

["hello", "i", "am", "leetcode", "hello"]
am
1

["hello", "i", "am", "leetcode", "hello"]
am
3

["hello", "i", "am", "leetcode", "hello"]
hello
1

["hello", "i", "am", "leetcode", "hello"]
am
0

["hello", "i", "am", "leetcode", "hello"]
leetcode
3

["hello", "i", "am", "leetcode", "hello"]
hello
3

["hello", "i", "am", "leetcode", "hello"]
i
4

["hello", "i", "am", "leetcode", "hello"]
am
2

["hello", "i", "am", "leetcode", "hello"]
i
0

[ "hello ", "i ", "am ", "leetcode ", "hello "]
hello
1

["hello", "i", "am", "leetcode", "hello"]
i
1

```python
def shortest_distance(words, target, startIndex):
    n = len(words)
    left, right, i = 0, 0, startIndex
    while True:
        if words[i] == target:
            return min(left, right)
        left += 1
        right += 1
        i = (i + 1) % n
        if left == n:
            break
    return -1
```


```cpp
int maxTastiness(vector<int>& price, int k) {
    sort(price.begin(), price.end());
    int max_tastiness = 0;
    for (int i = 0; i < price.size() - k + 1; i++) {
        int min_diff = INT_MAX;
        for (int j = i; j < i + k - 1; j++) {
            min_diff = min(min_diff, price[j + 1] - price[j]);
        }
        max_tastiness = max(max_tastiness, min_diff);
    }

    return max_tastiness;
}
```

```java
public int maxTastiness(int[] price, int k) {
    Arrays.sort(price);
    int max_tastiness = 0;
    for (int i = 0; i < price.length - k + 1; i++) {
        int min_diff = Integer.MAX_VALUE;
        for (int j = i; j < i + k - 1; j++) {
            min_diff = Math.min(min_diff, price[j + 1] - price[j]);
        }
        max_tastiness = Math.max(max_tastiness, min_diff);
    }

    return max_tastiness;
}
```


```cpp
#include <vector>

int countPartitions(std::vector<int>& nums, int k) {
    long long total_sum = 0;
    int n = nums.size();
    int mod = 1000000007;

    for (int num : nums) {
        total_sum += num;
    }

    if (total_sum < k * 2) {
        return 0;
    }

    std::vector<long long> dp(n + 1, 1);

    for (int i = 1; i <= k - 1; i++) {
        for (int j = n - 1; j >= 1; j--) {
            dp[j] = (dp[j] * j + dp[j - 1]) % mod;
        }
    }

    long long result = 0;

    for(int i = 0; i < n - 1; i++) {
        total_sum -= nums[i];
        if (total_sum >= k) {
            result = (result + dp[i + 1]) % mod;
        }
    }

    return (int) result;
}
```

```python
def countPartitions(nums, k):
    total_sum = sum(nums)
    n = len(nums)
    mod = 1000000007

    if total_sum < k * 2:
        return 0

    dp = [1] * (n + 1)

    for i in range(1, k):
        for j in range(n - 1, 0, -1):
            dp[j] = (dp[j] * j + dp[j - 1]) % mod

    result = 0

    for i in range(n - 1):
        total_sum -= nums[i]
        if total_sum >= k:
            result = (result + dp[i + 1]) % mod

    return result
```


```java
public int kBigIndices(int[] nums, int k) {
    int n = nums.length;
    int[] left = new int[n];
    int[] right = new int[n];

    for (int i = 1; i < n; i++) {
        if (nums[i] > nums[i - 1])
            left[i] = left[i - 1] + 1;

        int j = n - 1 - i;
        if (nums[j] < nums[j + 1])
            right[j] = right[j + 1] + 1;
    }

    int count = 0;
    for (int i = 0; i < n; i++)
        if (left[i] >= k && right[i] >= k)
            count++;

    return count;
}
```

```cpp
int kBigIndices(vector<int>& nums, int k) {
    int n = nums.size();
    vector<int> left(n, 0), right(n, 0);

    for (int i = 1; i < n; ++i) {
        if (nums[i] > nums[i - 1])
            left[i] = left[i - 1] + 1;

        int j = n - i - 1;
        if (nums[j] < nums[j + 1])
            right[j] = right[j + 1] + 1;
    }

    int count = 0;
    for (int i = 0; i < n; ++i)
        if (left[i] >= k && right[i] >= k)
            count++;

    return count;
}
```


```cpp
int digitsDividingNum(int num) {
    int count = 0, temp = num;
    while (temp > 0) {
        int digit = temp % 10;
        if (num % digit == 0) {
            count++;
        }
        temp /= 10;
    }
    return count;
}
```

```python
def digits_dividing_num(num):
    count = 0
    temp = num
    while temp > 0:
        digit = temp % 10
        if num % digit == 0:
            count += 1
        temp //= 10
    return count
```


```cpp
#include <set>

int countDistinctPrimeFactors(const std::vector<int>& nums) {
    std::set<int> prime_factors;
    for (const int n : nums) {
        for (int divisor = 2; divisor * divisor <= n; ++divisor) {
            if (n % divisor == 0) {
                prime_factors.insert(divisor);
                prime_factors.insert(n / divisor);
            }
        }
    }
    return prime_factors.size();
}
```

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

public int countDistinctPrimeFactors(int[] nums) {
    Set<Integer> prime_factors = new HashSet<>();
    for (int n : nums) {
        for (int divisor = 2; divisor * divisor <= n; ++divisor) {
            if (n % divisor == 0) {
                prime_factors.add(divisor);
                prime_factors.add(n / divisor);
            }
        }
    }
    return prime_factors.size();
}
```


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

int maxFrequencyScore(std::vector<int>& nums, int k) {
    int n = nums.size();
    int right = 0, count = 0, max_score = 0;
    long long score = 0;
    std::unordered_map<int, int> freqMap;

    for (int left = 0; left < n; ++left) {
        while (right < n && count < k) {
            score = (score + (long long)nums[right] * freqMap[nums[right]]) % 1000000007;
            freqMap[nums[right]]++;
            count++;
            right++;
        }

        max_score = std::max(max_score, (int)score);

        if (count == k) {
            score -= nums[left] * (freqMap[nums[left]] - 1);
            freqMap[nums[left]]--;
            count--;
        }
    }

    return max_score;
}
```

```java
import java.util.HashMap;

public int maxFrequencyScore(int[] nums, int k) {
    int n = nums.length;
    int right = 0, count = 0, max_score = 0;
    long score = 0;
    HashMap<Integer, Integer> freqMap = new HashMap<Integer, Integer>();

    for (int left = 0; left < n; ++left) {
        while (right < n && count < k) {
            score = (score + (long)nums[right] * freqMap.getOrDefault(nums[right], 0)) % 1000000007;
            freqMap.put(nums[right], freqMap.getOrDefault(nums[right], 0) + 1);
            count++;
            right++;
        }

        max_score = Math.max(max_score, (int)score);

        if (count == k) {
            score -= nums[left] * (freqMap.get(nums[left]) - 1);
            freqMap.put(nums[left], freqMap.get(nums[left]) - 1);
            count--;
        }
    }

    return max_score;
}
```


```cpp
#include <string>

std::string boxCategory(int length, int width, int height, int mass) {
    bool bulky = length >= 10000 || width >= 10000 || height >= 10000 || (long)length * width * height >= 1000000000;
    bool heavy = mass >= 100;

    if (bulky && heavy) return "Both ";
    if (bulky) return "Bulky ";
    if (heavy) return "Heavy ";
    return "Neither ";
}
```

length = 1000, width = 35, height = 700, mass = 300

Both Heavy Both Both Neither Both Both Both Both Heavy Both Heavy Both Bulky Both Both Both Heavy Both Both Heavy Both Heavy Both Both Both Heavy Heavy Both Both Neither Both Heavy Bulky Neither Both Neither Heavy Both Both Both Both Both Heavy

```python
def boxCategory(length: int, width: int, height: int, mass: int) -> str:
    bulky = length >= 10000 or width >= 10000 or height >= 10000 or int(length) * width * height >= 1000000000
    heavy = mass >= 100

    if bulky and heavy:
        return "Both "
    if bulky:
        return "Bulky "
    if heavy:
        return "Heavy "
    return "Neither "
```


```java
public int xorBeauty(int[] nums) {
    int n = nums.length;
    int maxXOR = 1024;
    int[] counter = new int[maxXOR];

    for (int num : nums) {
        counter[num % maxXOR]++;
    }

    int xor_beauty = 0;
    for (int i = 0; i < maxXOR; i++) {
        for (int j = i; j < maxXOR; j++) {
            int k = (i | j) & (~(i ^ j));
            if (k < maxXOR && k >= j) {
                int count = counter[i] * counter[j] * (i == j ? 1 : 2);
                if (k != i && k != j) {
                    count *= counter[k];
                }
                xor_beauty ^= count;
            }
        }
    }

    return xor_beauty;
}
```

```cpp
int xorBeauty(vector<int>& nums) {
    int n = nums.size();
    int maxXOR = 1024; // Maximum value for bitwise operations
    vector<int> counter(maxXOR, 0);

    for (int num : nums) {
        counter[num % maxXOR]++;
    }

    int xor_beauty = 0;
    for (int i = 0; i < maxXOR; i++) {
        for (int j = i; j < maxXOR; j++) {
            int k = (i | j) & (~(i ^ j));
            if (k < maxXOR && k >= j) {
                int count = counter[i] * counter[j] * (i == j ? 1 : 2);
                if (k != i && k != j) {
                    count *= counter[k];
                }
                xor_beauty ^= count;
            }
        }
    }

    return xor_beauty;
}
```


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

int maxScore(const vector<int>& nums, int k) {
    priority_queue<int> pq(nums.begin(), nums.end());
    int score = 0;

    for (int i = 0; i < k; i++) {
        int cur = pq.top();
        pq.pop();
        score += cur;
        pq.push(cur / 3);
    }

    return score;
}
```

```python
import heapq

def max_score(nums, k):
    pq = [-x for x in nums]
    heapq.heapify(pq)
    score = 0

    for _ in range(k):
        cur = -heapq.heappop(pq)
        score += cur
        heapq.heappush(pq, -cur // 3)

    return score
```


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

int getLastMoment(int n, int k, vector<vector<int>>& time) {
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> left, right;
    for (int i = 0; i < k; i++) {
        left.push({time[i][0] + time[i][2], i});
    }

    while (n) {
        while (!right.empty() && right.top().first <= left.top().first) {
            auto rightTop = right.top(); right.pop();
            left.push({rightTop.first + time[rightTop.second][0] + time[rightTop.second][2], rightTop.second});
        }
        auto leftTop = left.top(); left.pop();
        time[leftTop.second][2] += time[leftTop.second][3] + time[leftTop.second][0] + time[leftTop.second][1];
        right.push({leftTop.first + time[leftTop.second][1], leftTop.second});
        n--;
    }

    int lastMoment = -1;
    while (!right.empty()) {
        lastMoment = max(lastMoment, time[right.top().second][2]);
        right.pop();
    }
    return lastMoment;
}
```

```java
import java.util.*;

public int getLastMoment(int n, int k, int[][] time) {
    PriorityQueue<int[]> left = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));
    PriorityQueue<int[]> right = new PriorityQueue<>(Comparator.comparingInt(a -> a[0]));

    for (int i = 0; i < k; i++) {
        left.offer(new int[]{time[i][0] + time[i][2], i});
    }

    while (n > 0) {
        while (!right.isEmpty() && right.peek()[0] <= left.peek()[0]) {
            int[] rightTop = right.poll();
            left.offer(new int[]{rightTop[0] + time[rightTop[1]][0] + time[rightTop[1]][2], rightTop[1]});
        }
        int[] leftTop = left.poll();
        time[leftTop[1]][2] += time[leftTop[1]][3] + time[leftTop[1]][0] + time[leftTop[1]][1];
        right.offer(new int[]{leftTop[0] + time[leftTop[1]][1], leftTop[1]});
        n--;
    }

    int lastMoment = -1;
    while (!right.isEmpty()) {
        lastMoment = Math.max(lastMoment, time[right.poll()[1]][2]);
    }
    return lastMoment;
}
```


```python
def difference_between_element_and_digit_sum(nums):
    element_sum = sum(nums)
    digit_sum = sum(sum(int(digit) for digit in str(num)) for num in nums)
    return abs(element_sum - digit_sum)
```

```java
public int differenceBetweenElementAndDigitSum(int[] nums) {
    int element_sum = 0, digit_sum = 0;
    for (int num : nums) {
        element_sum += num;
        while (num > 0) {
            digit_sum += num % 10;
            num /= 10;
        }
    }
    return Math.abs(element_sum - digit_sum);
}
```


```java
public int goodSubarrays(int[] nums, int k) {
    Map<Integer, Integer> count = new HashMap<>();
    int result = 0, prefixSum = 0;

    count.put(0, 1);
    for (int num : nums) {
        prefixSum += num - 1;
        result += count.getOrDefault(prefixSum - k, 0);
        count.put(prefixSum, count.getOrDefault(prefixSum, 0) + 1);
    }

    return result;
}
```

```cpp
int goodSubarrays(vector<int>& nums, int k) {
    unordered_map<int, int> count;
    int result = 0, prefixSum = 0;

    count[0] = 1;
    for (int num : nums) {
        prefixSum += num - 1;
        result += count[prefixSum - k];
        count[prefixSum]++;
    }

    return result;
}
```


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

vector<vector<int>> adj;
vector<int> price;
vector<pair<vector<long long>, vector<long long>>> dp;

void dfs(int u, int p) {
    dp[u].first[0] = price[u];
    dp[u].first[1] = 0;
    dp[u].second[0] = price[u];
    dp[u].second[1] = 0;

    for (int v : adj[u]) {
        if (v == p) continue;
        dfs(v, u);
        dp[u].first.push_back(dp[v].first[0] + price[u] - dp[v].second[0]);
        dp[u].first.push_back(dp[v].first[1]);
        dp[u].second.push_back(dp[v].second[0] + price[u] - dp[v].first[0]);
        dp[u].second.push_back(dp[v].second[1]);

        sort(dp[u].first.begin(), dp[u].first.end());
        sort(dp[u].second.begin(), dp[u].second.end());
    }
}

int getMaxCost(int n, vector<vector<int>>& edges, vector<int>& _price) {
    adj.resize(n);
    price = _price;
    dp.resize(n, pair<vector<long long>, vector<long long>>(vector<long long>(2), vector<long long>(2)));

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

    dfs(0, -1);

    long long ans = 0;
    for (int i = 0; i < n; ++i) {
        ans = max(ans, dp[i].first.back() - dp[i].second.back());
    }

    return ans;
}
```

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

class Solution {
    List<Integer>[] adj;
    int[] price;
    long[][][] dp;

    void dfs(int u, int p) {
        dp[u][0] = new long[]{price[u], 0};
        dp[u][1] = new long[]{price[u], 0};

        for (int v : adj[u]) {
            if (v == p) continue;
            dfs(v, u);
            long[] tmpF = new long[]{dp[v][0][0] + price[u] - dp[v][1][0], dp[v][0][1]};
            long[] tmpS = new long[]{dp[v][1][0] + price[u] - dp[v][0][0], dp[v][1][1]};

            Arrays.sort(tmpF);
            Arrays.sort(tmpS);

            dp[u][0] = tmpF;
            dp[u][1] = tmpS;
        }
    }

    public int getMaxCost(int n, int[][] edges, int[] _price) {
        adj = new ArrayList[n];
        price = _price;
        dp = new long[n][2][];

        for (int i = 0; i < n; i++) {
            adj[i] = new ArrayList<>();
        }

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

        dfs(0, -1);

        long ans = 0;
        for (int i = 0; i < n; ++i) {
            ans = Math.max(ans, dp[i][0][1] - dp[i][1][1]);
        }

        return (int) ans;
    }
}
```


```python
def min_changes(nums1, nums2, k):
    n = len(nums1)
    operations = 0
    for i in range(n):
        diff = abs(nums1[i] - nums2[i])
        if diff % k != 0:
            return -1
        operations += diff // k
    return operations
```

```cpp
int minChanges(vector<int>& nums1, vector<int>& nums2, int k) {
    int n = nums1.size();
    int operations = 0;
    for (int i = 0; i < n; ++i) {
        int diff = abs(nums1[i] - nums2[i]);
        if (diff % k != 0) return -1;
        operations += diff / k;
    }
    return operations;
}
```


```java
public int maxScore(int[] nums1, int[] nums2, int k) {
    int n = nums1.length;
    int res = 0;
    int sum_n1 = 0, min_n2 = nums2[0];
    for (int i = 0, j = 0; j < n; j++) {
        sum_n1 += nums1[j];
        min_n2 = Math.min(min_n2, nums2[j]);
        if (j - i + 1 > k) sum_n1 -= nums1[i++];
        if (j + 1 >= k) res = Math.max(res, sum_n1 * min_n2);
    }
    return res;
}
```

```cpp
int maxScore(vector<int>& nums1, vector<int>& nums2, int k) {
    int n = nums1.size();
    int res = 0;
    int sum_n1 = 0, min_n2 = nums2[0];
    for (int i = 0, j = 0; j < n; ++j) {
        sum_n1 += nums1[j];
        min_n2 = min(min_n2, nums2[j]);
        if (j - i + 1 > k) sum_n1 -= nums1[i++];
        if (j + 1 >= k) res = max(res, sum_n1 * min_n2);
    }
    return res;
}
```


```java
import java.util.*;

class Solution {
    public int[][] sortStudents(int[][] score, int k) {
        Arrays.sort(score, (a, b) -> b[k] - a[k]);
        return score;
    }
}
```

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

vector<vector<int>> sortStudents(vector<vector<int>>& score, int k) {
    sort(score.begin(), score.end(), [k] (const vector<int>& a, const vector<int>& b) {
        return a[k] > b[k];
    });
    return score;
}
```


```cpp
int minCost(vector<int>& nums, int k) {
    int n = nums.size(), INF = 1e9 + 7;
    vector<int> count(1001, 0), dp(n + 1, 0); // count for frequency, dp for dynamic programming

    for (int i = 0, j = 0; j < n; ++j) {
        ++count[nums[j]];

        if (count[nums[j]] == 2) // if occurrence is 2, change dp
            dp[j + 1] = dp[i] + k + (j - i + 1);
        else if (count[nums[j]] > 2) // if occurrence is more than 2
            dp[j + 1] = min(dp[j], dp[j - 1] - (count[nums[j]] - 2));
        else
            dp[j + 1] = dp[j] + getCost(j, count) + k;

        while (i < j + 1 && count[nums[i]] >= 2) {
            --count[nums[i]];
            ++i; // update first pointer i when nums[i] has occurred more than once
        }
    }

    return dp[n];
}

int getCost(int j, vector<int> &count) {
    return count[nums[j]] == 1 ? 1 : 0;
}
```

```python
def minCost(nums: List[int], k: int) -> int:
    n = len(nums)
    count = [0] * 1001
    dp = [0] * (n + 1)

    i = 0
    for j in range(n):
        count[nums[j]] += 1

        if count[nums[j]] == 2:
            dp[j + 1] = dp[i] + k + (j - i + 1)
        elif count[nums[j]] > 2:
            dp[j + 1] = min(dp[j], dp[j - 1] + 1)
        else:
            dp[j + 1] = dp[j] + 1

        while i <= j and count[nums[i]] >= 2:
            count[nums[i]] -= 1
            i += 1

    return dp[n] + n * k
```


```java
import java.util.Arrays;

public double maxValue(int[][] items, int capacity) {
    Arrays.sort(items, (a, b) -> Double.compare((double) b[0] / b[1], (double) a[0] / a[1]));

    double maxTotalPrice = 0;
    for (int[] item : items) {
        if (capacity >= item[1]) {
            capacity -= item[1];
            maxTotalPrice += item[0];
        }
        else {
            maxTotalPrice += (double) item[0] * capacity / item[1];
            break;
        }
    }

    return maxTotalPrice;
}
```

```python
def maxValue(items, capacity):
    items.sort(key=lambda x: x[0] / x[1], reverse=True)

    maxTotalPrice = 0
    for item in items:
        if capacity >= item[1]:
            capacity -= item[1]
            maxTotalPrice += item[0]
        else:
            maxTotalPrice += item[0] * capacity / item[1]
            break

    return maxTotalPrice
```


```java
import java.math.BigInteger;

public class Main {
    private final static BigInteger MOD = new BigInteger("1000000007");

    public static BigInteger waysToCollide(int n) {
        BigInteger powerOf2 = BigInteger.ONE.shiftLeft(n).mod(MOD);
        return powerOf2.subtract(BigInteger.valueOf(n)).subtract(BigInteger.ONE).add(MOD).mod(MOD);
    }
}
```

```python
def ways_to_collide(n):
    MOD = 10**9 + 7
    return (pow(2, n, MOD) - n - 1 + MOD) % MOD
```


```java
public int increasingQuadruplets(int[] nums) {
    int n = nums.length, count = 0;
    for(int i = 0; i < n - 3; i++) {
        for(int j = i + 1; j < n - 2; j++) {
            for(int k = j + 1; k < n - 1; k++) {
                if(nums[i] < nums[k] && nums[k] < nums[j]) {
                    for(int l = k + 1; l < n; l++) {
                        if(nums[j] < nums[l]) {
                            count++;
                        }
                    }
                }
            }
        }
    }
    return count;
}
```

```javascript
function increasingQuadruplets(nums) {
    const n = nums.length;
    let count = 0;
    for(let i = 0; i < n - 3; i++) {
        for(let j = i + 1; j < n - 2; j++) {
            for(let k = j + 1; k < n - 1; k++) {
                if(nums[i] < nums[k] && nums[k] < nums[j]) {
                    for(let l = k + 1; l < n; l++) {
                        if(nums[j] < nums[l]) {
                            count++;
                        }
                    }
                }
            }
        }
    }
    return count;
}
```


```cpp
#include <vector>

std::vector<int> separateDigits(const std::vector<int>& nums) {
    std::vector<int> answer;
    for(auto num : nums) {
        std::vector<int> digits;
        while(num) {
            digits.insert(digits.begin(), num % 10);
            num /= 10;
        }
        answer.insert(answer.end(), digits.begin(), digits.end());
    }
    return answer;
}
```

```python
def separate_digits(nums):
    answer = []
    for num in nums:
        digits = [int(d) for d in str(num)]
        answer.extend(digits)
    return answer
```


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

int maxChosenIntegers(vector<int>& banned, int n, int maxSum) {
    unordered_set<int> bannedSet(banned.begin(), banned.end());
    int count = 0, sum = 0;
    for (int i = n; i >= 1 && maxSum - sum >= i; --i) {
        if (bannedSet.find(i) == bannedSet.end()) {
            sum += i;
            ++count;
        }
    }
    return count;
}
```

```python
def max_chosen_integers(banned, n, max_sum):
    banned_set = set(banned)
    count = 0
    total_sum = 0
    for i in range(n, 0, -1):
        if i not in banned_set and max_sum - total_sum >= i:
            total_sum += i
            count += 1
    return count
```


```python
import math

def giftsRemaining(gifts, k):
    for i in range(k):
        gifts.sort()
        max_index = len(gifts) - 1
        gifts[max_index] -= int(math.sqrt(gifts[max_index]))
    return sum(gifts)
```

```java
import java.util.Arrays;

public int giftsRemaining(int[] gifts, int k) {
    for (int i = 0; i < k; i++) {
        Arrays.sort(gifts);
        int maxIndex = gifts.length - 1;
        gifts[maxIndex] -= (int) Math.sqrt(gifts[maxIndex]);
    }
    int remaining_gifts = 0;
    for (int gift : gifts) remaining_gifts += gift;
    return remaining_gifts;
}
```


```python
def min_cost_to_equal_baskets(basket1, basket2):
    diff_count = {}
    for i in range(len(basket1)):
        diff = basket1[i] - basket2[i]
        diff_count[diff] = diff_count.get(diff, 0) + 1

    min_cost = float('inf')
    for diff, count in diff_count.items():
        if count == diff_count.get(-diff, 0):
            cost = sum(min(basket1[i], basket2[i]) for i in range(len(basket1)) if basket1[i] - basket2[i] == diff)
            min_cost = min(min_cost, cost)

    return -1 if min_cost == float('inf') else min_cost // 2
```

```java
public int minCostToEqualBaskets(int[] basket1, int[] basket2) {
    Map<Integer, Integer> diffCount = new HashMap<>();
    for (int i = 0; i < basket1.length; i++) {
        diffCount.put(basket1[i] - basket2[i], diffCount.getOrDefault(basket1[i] - basket2[i], 0) + 1);
    }

    int minCost = Integer.MAX_VALUE, cost = 0;
    for (Map.Entry<Integer, Integer> entry : diffCount.entrySet()) {
        if (entry.getValue().equals(diffCount.get(-entry.getKey()))) {
            cost = 0;
            for (int i = 0; i < basket1.length; i++) {
                if (basket1[i] - basket2[i] == entry.getKey()) {
                    cost += Math.min(basket1[i], basket2[i]);
                }
            }
            minCost = Math.min(minCost, cost);
        }
    }

    return minCost == Integer.MAX_VALUE ? -1 : minCost / 2;
}
```


```python
def concatenationValue(nums):
    value = 0
    while nums:
        n = len(nums)
        if n == 1:
            value += nums[0]
            nums.pop()
        else:
            value += int(str(nums[0]) + str(nums[-1]))
            nums.pop(0)
            nums.pop()
    return value
```

```java
public int concatenationValue(int[] nums) {
    int value = 0;
    int n = nums.length;
    for (int i = 0; i < n; i += 2) {
        if (i == n - 1 - i) {
            value += nums[i];
        } else {
            value += Integer.parseInt(String.valueOf(nums[i]) + String.valueOf(nums[n - 1 - i]));
        }
    }
    return value;
}
```


```python
def count_fair_pairs(nums, lower, upper):
    n = len(nums)
    fair_pairs = 0
    for i in range(n):
        for j in range(i+1, n):
            if lower <= nums[i] + nums[j] <= upper:
                fair_pairs += 1
    return fair_pairs
```

```java
public int countFairPairs(int[] nums, int lower, int upper) {
    int n = nums.length;
    int fair_pairs = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            if ((lower <= nums[i] + nums[j]) && (nums[i] + nums[j] <= upper)) {
                fair_pairs++;
            }
        }
    }
    return fair_pairs;
}
```


```python
def minScore(s, t):
    m, n = len(s), len(t)
    dp = [[1e6]*(n+1) for _ in range(m+1)]
    dp[0][0] = 0
    for i in range(m):
        for j in range(n):
            if s[i] == t[j]:
                dp[i+1][j+1] = min(dp[i+1][j+1], dp[i][j])
            else:
                dp[i+1][j] = min(dp[i+1][j], dp[i][j] + 1)
    ans = 1e6
    for i in range(m):
        ans = min(ans, dp[i+1][n])
    return int(ans)
```

```java
public int minScore(String s, String t) {
    int m = s.length(), n = t.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 0; i <= m; i++) Arrays.fill(dp[i], 1000000);
    dp[0][0] = 0;
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (s.charAt(i) == t.charAt(j)) {
                dp[i + 1][j + 1] = Math.min(dp[i + 1][j + 1], dp[i][j]);
            } else {
                dp[i + 1][j] = Math.min(dp[i + 1][j], dp[i][j] + 1);
            }
        }
    }
    int ans = 1000000;
    for (int i = 0; i < m; i++) {
        ans = Math.min(ans, dp[i + 1][n]);
    }
    return ans;
}
```


```cpp
int diffMaxMin(int num) {
    int maxRemap = 1, minRemap = 9;
    string numStr = to_string(num);
    for (char c : numStr) {
        int digit = c - '0';
        maxRemap = max(maxRemap, 9 - digit);
        if (digit != 0) {
            minRemap = min(minRemap, digit);
        }
    }
    int maxValue = num + maxRemap * (numStr.length() - count(numStr.begin(), numStr.end(), '9' - maxRemap));
    int minValue = num - minRemap * count(numStr.begin(), numStr.end(), minRemap + '0');
    return maxValue - minValue;
}
```

```python
def diffMaxMin(num):
    max_remap = 1
    min_remap = 9
    num_str = str(num)

    for c in num_str:
        digit = int(c)
        max_remap = max(max_remap, 9 - digit)
        if digit != 0:
            min_remap = min(min_remap, digit)

    max_value = num + max_remap * (len(num_str) - num_str.count(str(9 - max_remap)))
    min_value = num - min_remap * num_str.count(str(min_remap))
    return max_value - min_value
```


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

int minScoreAfterChange(std::vector<int>& nums) {
    int n = nums.size();
    int first_min = nums[0], second_min = nums[1], last_max = nums[n - 1], second_last_max = nums[n - 2];

    for (int i = 1; i < n - 1; i++) {
        first_min = std::min(first_min, nums[i]);
        second_min = std::min(second_min, nums[i + 1]);
        last_max = std::max(last_max, nums[i]);
        second_last_max = std::max(second_last_max, nums[i - 1]);
    }

    int low = std::min(std::min(first_min, last_max), std::min(second_min, second_last_max));
    int high = std::max(std::max(first_min, last_max), std::max(second_min, second_last_max));

    return high - low;
}
```

```python
def min_score_after_change(nums):
    n = len(nums)
    first_min, second_min, last_max, second_last_max = nums[0], nums[1], nums[-1], nums[-2]

    for i in range(1, n - 1):
        first_min = min(first_min, nums[i])
        second_min = min(second_min, nums[i + 1])
        last_max = max(last_max, nums[i])
        second_last_max = max(second_last_max, nums[i - 1])

    low = min(min(first_min, last_max), min(second_min, second_last_max))
    high = max(max(first_min, last_max), max(second_min, second_last_max))

    return high - low
```


```cpp
int minNonExpressibleInteger(vector<int>& nums) {
    int result = 1;
    sort(nums.begin(), nums.end());
    for (int num : nums) {
        if (num > result) break;
        result += num;
    }
    return result;
}
```

```python
def min_non_expressible_integer(nums):
    result = 1
    nums.sort()
    for num in nums:
        if num > result:
            break
        result += num
    return result
```


```python
def solve(nums1, nums2, queries):
    res = []
    for q in queries:
        if q[0] == 1:
            for i in range(q[1], q[2] + 1):
                nums1[i] ^= 1
        elif q[0] == 2:
            for i in range(len(nums1)):
                nums2[i] += nums1[i] * q[1]
        elif q[0] == 3:
            res.append(sum(nums2))
    return res
```

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

public List<Integer> solve(int[] nums1, int[] nums2, int[][] queries) {
    List<Integer> res = new ArrayList<>();
    for (int[] q : queries) {
        if (q[0] == 1) {
            for (int i = q[1]; i <= q[2]; i++) {
                nums1[i] ^= 1;
            }
        } else if (q[0] == 2) {
            for (int i = 0; i < nums1.length; i++) {
                nums2[i] += nums1[i] * q[1];
            }
        } else if (q[0] == 3) {
            int sum = 0;
            for (int num : nums2) {
                sum += num;
            }
            res.add(sum);
        }
    }
    return res;
}
```


```python
def minOperations(n: int) -> int:
    operations = 0
    while n:
        operations += n % 2
        n //= 2
    return operations
```

```java
public int minOperations(int n) {
    int operations = 0;
    while (n > 0) {
        operations += n % 2;
        n /= 2;
    }
    return operations;
}
```


```python
def countSquareFreeSubsets(nums):
    from collections import Counter
    counter = Counter(nums)
    MOD = 10**9 + 7

    dp = [[0] * 1001 for _ in range(61)]
    dp[0][0] = 1
    idx = 0
    for num, freq in counter.items():
        idx += 1
        for sq in range(61):
            for ns in range(1001 - freq):
                dp[idx][ns + freq] += dp[idx - 1][ns] * ((1 << freq) - 1) % MOD
                dp[idx][ns + freq] %= MOD
                dp[idx][ns] += dp[idx - 1][ns]
                dp[idx][ns] %= MOD

                if (sq // num) % 2 == 1:
                    dp[idx][ns + freq] -= dp[idx - 1][ns] * ((1 << (freq - 1)) - 1) % MOD
                    if dp[idx][ns + freq] < 0:
                        dp[idx][ns + freq] += MOD
    return dp[idx][0]
```

```java
import java.util.HashMap;

public int countSquareFreeSubsets(int[] nums) {
    HashMap<Integer, Integer> counter = new HashMap<>();
    for (int num : nums) {
        counter.put(num, counter.getOrDefault(num, 0) + 1);
    }

    long[][] dp = new long[61][1001];
    int idx = 0;
    int MOD = 1000000000 + 7;
    dp[0][0] = 1;
    for (int num : counter.keySet()) {
        int freq = counter.get(num);
        idx++;
        for (int sq = 0; sq <= 60; sq++) {
            for (int ns = 0; ns + freq <= 1000; ns++) {
                dp[idx][ns + freq] += (dp[idx - 1][ns] * ((1L << freq) - 1)) % MOD;
                dp[idx][ns + freq] %= MOD;
                dp[idx][ns] += dp[idx - 1][ns];
                dp[idx][ns] %= MOD;

                if ((sq / num) % 2 == 1) {
                    dp[idx][ns + freq] -= dp[idx - 1][ns] * ((1L << (freq - 1)) - 1) % MOD;
                    if(dp[idx][ns + freq] < 0)
                        dp[idx][ns + freq] += MOD;
                }
            }
        }
    }
    return (int)dp[idx][0];
}
```


```java
public String smallestWordForLCP(int[][] lcp) {
    int n = lcp.length;
    char[] word = new char[n];
    Arrays.fill(word, 'a');
    for (int i = 1; i < n; ++i)
        for (int j = 1; j < n; ++j) {
            if (lcp[i][j] > Math.min(lcp[i - 1][j], lcp[i][j - 1])) {
                word[i + lcp[i][j] - 1] = (char) Math.max(word[i + lcp[i][j] - 1], word[i - 1] + 1);
            } else if (lcp[i][j] < Math.min(lcp[i - 1][j], lcp[i][j - 1])) {
                return "";
            }
        }
    return new String(word);
}
```

"aaaa" "abcd" "" "aaaa" "aaabb" "aaab" "" "" "aaab" "aaaa" "" "" "aaab" "aaab" "" "aaaa" "" "aaaa" "aaab" "aaab" "aaaa" "" "aaaa" "aaaa" "" "" "" "aaab" "aaaa" "" "aaab" "aaaa" "aaab" "" "" "" "aaaa" "aaaa" "aaab" "aaab" "abbb" "aaaa" "aaab" "abcd" "" "" "aaaa" "aaab" "" "aaaa" "aaaa" "aaaa" "aaab" "aaaa" "" "" "aaaa"

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

std::string smallestWordForLCP(std::vector<std::vector<int>>& lcp) {
    int n = lcp.size();
    std::string word(n, 'a');
    for (int i = 1; i < n; ++i)
        for (int j = 1; j < n; ++j) {
            if (lcp[i][j] > std::min(lcp[i - 1][j], lcp[i][j - 1])) {
                word[i + lcp[i][j] - 1] = std::max(word[i + lcp[i][j] - 1], (char) (word[i - 1] + 1));
            } else if (lcp[i][j] < std::min(lcp[i - 1][j], lcp[i][j - 1])) {
                return "";
            }
        }
    return word;
}
```


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

vector<int> getAnswer(vector<int>& nums) {
    int n = nums.size();
    vector<int> leftSum(n, 0), rightSum(n, 0), answer(n, 0);

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

    for (int i = n - 2; i >= 0; i--) {
        rightSum[i] = rightSum[i + 1] + nums[i + 1];
    }

    for (int i = 0; i < n; i++) {
        answer[i] = abs(leftSum[i] - rightSum[i]);
    }

    return answer;
}
```

```python
def get_answer(nums):
    n = len(nums)
    left_sum, right_sum, answer = [0] * n, [0] * n, [0] * n

    for i in range(1, n):
        left_sum[i] = left_sum[i - 1] + nums[i - 1]

    for i in range(n - 2, -1, -1):
        right_sum[i] = right_sum[i + 1] + nums[i + 1]

    for i in range(n):
        answer[i] = abs(left_sum[i] - right_sum[i])

    return answer
```


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

const int MOD = 1e9 + 7;

int totalWaysToSplitRanges(std::vector<std::vector<int>>& ranges) {
    std::sort(ranges.begin(), ranges.end(), [](const std::vector<int>& a, const std::vector<int>& b) {
        return a[1] < b[1];
    });
    int overlapping = 0, non_overlapping = 1, prev_end = -1;
    for (const auto& range : ranges) {
        if (range[0] <= prev_end) {
            overlapping++;
        } else {
            non_overlapping++;
        }
        prev_end = std::max(prev_end, range[1]);
    }
    long result = 1;
    for (int i = 1; i <= overlapping; ++i) {
        result = (result * 2) % MOD;
    }
    return result;
}
```

```java
import java.util.Arrays;

public int totalWaysToSplitRanges(int[][] ranges) {
    final int MOD = 1000000007;
    Arrays.sort(ranges, (a, b) -> Integer.compare(a[1], b[1]));
    int overlapping = 0, non_overlapping = 1, prev_end = -1;

    for (int[] range : ranges) {
        if (range[0] <= prev_end) {
            overlapping++;
        } else {
            non_overlapping++;
        }
        prev_end = Math.max(prev_end, range[1]);
    }
    long result = 1;
    for (int i = 1; i <= overlapping; ++i) {
        result = (result * 2) % MOD;
    }
    return (int)result;
}
```


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

int possibleRoots(const std::vector<std::vector<int>>& edges, const std::vector<std::vector<int>>& guesses, int k) {
    int n = edges.size() + 1;
    std::vector<int> in_degree(n, 0);
    std::unordered_set<int> guess_parents;

    for (const auto& guess : guesses) {
        guess_parents.insert(guess[0]);
    }

    for (const auto& edge : edges) {
        in_degree[edge[1]]++;
    }

    int possible_roots = 0;
    for (int i = 0; i < n; ++i) {
        if (in_degree[i] == 0) {
            if (k == 0 || guess_parents.find(i) != guess_parents.end()) {
                possible_roots++;
            }
        } else if (in_degree[i] == 1 && guesses.size() - k < in_degree[i]) {
            possible_roots++;
        }
    }
    return possible_roots;
}
```

```python
def possibleRoots(edges, guesses, k):
    n = len(edges) + 1
    in_degree = [0] * n
    guess_parents = set()

    for guess in guesses:
        guess_parents.add(guess[0])

    for edge in edges:
        in_degree[edge[1]] += 1

    possible_roots = 0
    for i in range(n):
        if in_degree[i] == 0:
            if k == 0 or i in guess_parents:
                possible_roots += 1
        elif in_degree[i] == 1 and len(guesses) - k < in_degree[i]:
            possible_roots += 1

    return possible_roots
```


```cpp
int pillowHolder(int n, int time) {
    time %= (2 * n - 2);
    if (time <= n - 1) return time + 1;
    else return 2 * n - time - 1;
}
```

```python
def pillowHolder(n, time):
    time %= (2 * n - 2)
    if time <= n - 1:
        return time + 1
    else:
        return 2 * n - time - 1
```


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

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
};

int kthLargestLevelSum(TreeNode* root, int k) {
    std::vector<int> level_sums;
    std::queue<TreeNode*> q;
    q.push(root);

    while (!q.empty()) {
        int level_sum = 0;
        int level_size = q.size();
        for (int i = 0; i < level_size; ++i) {
            TreeNode* node = q.front(); q.pop();
            level_sum += node->val;

            if (node->left) q.push(node->left);
            if (node->right) q.push(node->right);
        }

        level_sums.push_back(level_sum);
    }

    std::sort(level_sums.begin(), level_sums.end(), std::greater<int>());
    return (k > level_sums.size() ? -1 : level_sums[k-1]);
}
```

[1, None, 2, None, 3, None, 4, None, 5]
3

```python
from queue import Queue

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

def kthLargestLevelSum(root, k):
    level_sums = []
    q = Queue()
    q.put(root)

    while not q.empty():
        level_sum = 0
        level_size = q.qsize()
        for i in range(level_size):
            node = q.get()
            level_sum += node.val

            if node.left:
                q.put(node.left)
            if node.right:
                q.put(node.right)

        level_sums.append(level_sum)

    level_sums.sort(reverse=True)
    return level_sums[k-1] if k <= len(level_sums) else -1
```


```cpp
#include <vector>

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

int findValidSplit(const std::vector<int>& nums) {
    int n = nums.size();
    std::vector<int> prefix(n);
    std::vector<int> suffix(n);

    prefix[0] = nums[0];
    suffix[n - 1] = nums[n - 1];

    for (int i = 1; i < n; ++i)
        prefix[i] = prefix[i - 1] * nums[i];

    for (int i = n - 2; i >= 0; --i)
        suffix[i] = suffix[i + 1] * nums[i];

    for (int i = 0; i < n - 1; ++i) {
        if (gcd(prefix[i], suffix[i + 1]) == 1)
            return i;
    }

    return -1;
}
```

```java
public int findValidSplit(int[] nums) {
    int n = nums.length;
    int[] prefix = new int[n];
    int[] suffix = new int[n];

    prefix[0] = nums[0];
    suffix[n - 1] = nums[n - 1];

    for (int i = 1; i < n; ++i)
        prefix[i] = prefix[i - 1] * nums[i];

    for (int i = n - 2; i >= 0; --i)
        suffix[i] = suffix[i + 1] * nums[i];

    for (int i = 0; i < n - 1; ++i) {
        if (gcd(prefix[i], suffix[i + 1]) == 1)
            return i;
    }

    return -1;
}

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


```java
public int numberOfWays(int target, int[][] types) {
    int MOD = 1000000007;
    int[] dp = new int[target + 1];
    dp[0] = 1;
    for (int[] type : types) {
        int count = type[0], marks = type[1];
        int[] dptmp = new int[target + 1];
        for (int i = 0; i <= target; ++i) {
            for (int j = 0; j <= count && j * marks + i <= target; ++j) {
                dptmp[i + j * marks] = (dptmp[i + j * marks] + dp[i]) % MOD;
            }
        }
        dp = dptmp;
    }
    return dp[target];
}
```

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

const int MOD = 1e9 + 7;

int numberOfWays(int target, vector<vector<int>>& types) {
    vector<int> dp(target + 1, 0);
    dp[0] = 1;
    for(auto &type : types) {
        int count = type[0], marks = type[1];
        vector<int> dptmp(target + 1, 0);
        for(int i = 0; i <= target; ++i) {
            for(int j = 0; j <= count && j * marks + i <= target; ++j) {
                dptmp[i + j * marks] = (dptmp[i + j * marks] + dp[i]) % MOD;
            }
        }
        dp = dptmp;
    }
    return dp[target];
}
```


```python
def is_vowel(c):
  return c in 'aeiou'

def count_vowel_strings(words, left, right):
  count = 0
  for i in range(left, right + 1):
    if is_vowel(words[i][0]) and is_vowel(words[i][-1]):
      count += 1
  return count
```

words = \[ "are ", "amy ", "u "\], left = 0, right = 2

["papaya", "quince", "rhubarb", "strawberry", "tomato"]
1
2

["papaya", "quince", "rhubarb", "strawberry", "tomato"]
0
1

["papaya", "quince", "rhubarb", "strawberry", "tomato"]
1
3

["ugli fruit", "vanilla bean", "watermelon", "xigua", "yellow passionfruit"]
0
3

["zucchini", "dragon fruit", "grapefruit", "honeydew", "jackfruit"]
1
3

["zucchini", "dragon fruit", "grapefruit", "honeydew", "jackfruit"]
0
2

["kiwifruit", "lime", "mango", "nectarine", "orange"]
0
1

["papaya", "quince", "rhubarb", "strawberry", "tomato"]
3
4

["orange", "pineapple", "watermelon", "peach", "grapefruit"]
0
4

["kiwifruit", "lime", "mango", "nectarine", "orange"]
0
2

["ugli fruit", "vanilla bean", "watermelon", "xigua", "yellow passionfruit"]
2
4

["blueberry", "raspberry", "blackberry", "strawberry", "boysenberry"]
2
2

["olive", "pomegranate", "quince", "raspberry", "star fruit"]
0
1

["tomato", "ugli fruit", "vanilla bean", "watermelon", "xigua"]
2
4

["papaya", "quince", "rhubarb", "strawberry", "tomato"]
2
3

["zucchini", "dragon fruit", "grapefruit", "honeydew", "jackfruit"]
0
1

["passionfruit", "lychee", "mulberry", "kumquat", "acai"]
0
0

["kiwifruit", "lime", "mango", "nectarine", "orange"]
2
4

["kiwifruit", "lime", "mango", "nectarine", "orange"]
1
3

["zucchini", "dragon fruit", "grapefruit", "honeydew", "jackfruit"]
3
4

["papaya", "quince", "rhubarb", "strawberry", "tomato"]
2
4

["ugli fruit", "vanilla bean", "watermelon", "xigua", "yellow passionfruit"]
2
3

["apple", "banana", "cherry", "date", "elderberry"]
1
3

["papaya", "quince", "rhubarb", "strawberry", "tomato"]
1
4

["ugli fruit", "vanilla bean", "watermelon", "xigua", "yellow passionfruit"]
0
2

["zucchini", "dragon fruit", "grapefruit", "honeydew", "jackfruit"]
1
4

["kiwifruit", "lime", "mango", "nectarine", "orange"]
2
3

["mango", "papaya", "jackfruit", "custard apple", "star fruit"]
4
4

["yellow passionfruit", "zucchini", "dragon fruit", "grapefruit", "jackfruit"]
0
1

["cantaloupe", "dragonfruit", "ugli fruit", "jack fruit", "nectarine"]
3
4

["ugli fruit", "vanilla bean", "watermelon", "xigua", "yellow passionfruit"]
3
4

["cranberry", "durian", "feijoa", "guava", "honeydew"]
1
3

```java
public boolean isVowel(char c) {
  return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
}

public int countVowelStrings(String[] words, int left, int right) {
  int count = 0;
  for (int i = left; i <= right; i++) {
    if (isVowel(words[i].charAt(0)) && isVowel(words[i].charAt(words[i].length() - 1))) {
      count++;
    }
  }
  return count;
}
```


```cpp
int maxScore(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int result = 0, prefixSum = 0;
    for (int i = 0; i < nums.size(); ++i) {
        if (prefixSum + nums[i] > 0) {
            ++result;
            prefixSum += nums[i];
        }
    }
    return result;
}
```

```java
public int maxScore(int[] nums) {
    Arrays.sort(nums);
    int result = 0, prefixSum = 0;
    for (int i = 0; i < nums.length; ++i) {
        if (prefixSum + nums[i] > 0) {
            ++result;
            prefixSum += nums[i];
        }
    }
    return result;
}
```


```cpp
int beautifulSubarrays(vector<int>& nums) {
    vector<int> odd(20, 0);
    vector<int> even(20, 0);
    even[0] = 1;

    for (int num : nums) {
        bool parity = __builtin_parity(num);
        for (int i = 19; i >= 0; i--) {
            int mask = 1 << i;
            if (num & mask) {
                if (parity) swap(odd[i], even[i]);
                odd[i]++;
            } else {
                if (!parity) swap(odd[i], even[i]);
                even[i]++;
            }
            num -= (num & mask);
        }
    }

    long long ans = 0;
    for (int i = 0; i < 20; i++) ans += (long long)even[i] * (even[i] - 1) / 2;
    return ans;
}
```

```java
public int beautifulSubarrays(int[] nums) {
    int[] odd = new int[20];
    int[] even = new int[20];
    even[0] = 1;

    for (int num : nums) {
        boolean parity = Integer.bitCount(num) % 2 == 1;
        for (int i = 19; i >= 0; i--) {
            int mask = 1 << i;
            if ((num & mask) != 0) {
                if (parity) {
                    int temp = odd[i];
                    odd[i] = even[i];
                    even[i] = temp;
                }
                odd[i]++;
            } else {
                if (!parity) {
                    int temp = odd[i];
                    odd[i] = even[i];
                    even[i] = temp;
                }
                even[i]++;
            }
            num -= (num & mask);
        }
    }

    long ans = 0;
    for (int i = 0; i < 20; i++) ans += (long)even[i] * (even[i] - 1) / 2;
    return (int) ans;
}
```


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

int min_time_on(vector<vector<int>>& tasks) {
    vector<vector<int>> intervals;
    for (const auto& task : tasks) {
        intervals.push_back({task[1] + 1, task[2]});
    }
    sort(intervals.begin(), intervals.end());

    vector<int> dp(2001, 0);
    for (const auto& interval : intervals) {
        for (int i = 2000; i >= interval[0]; --i) {
            dp[i] = max(dp[i], dp[i - interval[1]] + interval[1]);
        }
    }
    return dp.back();
}
```

```python
def min_time_on(tasks):
    intervals = sorted([[task[1] + 1, task[2]] for task in tasks])

    dp = [0] * 2001
    for interval in intervals:
        for i in range(2000, interval[0] - 1, -1):
            dp[i] = max(dp[i], dp[i - interval[1]] + interval[1])

    return dp[-1]
```


```java
public int maxGreatness(int[] nums) {
    Arrays.sort(nums);
    int greatness = 0;
    for (int i = 1; i < nums.length; ++i) {
        if (nums[i - 1] < nums[i]) {
            int temp = nums[i - 1];
            nums[i - 1] = nums[i];
            nums[i] = temp;
            ++greatness;
        }
    }
    return greatness;
}
```

```python
def max_greatness(nums):
    nums.sort()
    greatness = 0
    for i in range(1, len(nums)):
        if nums[i - 1] < nums[i]:
            nums[i - 1], nums[i] = nums[i], nums[i - 1]
            greatness += 1
    return greatness
```


```cpp
int calculateScore(vector<int>& nums) {
    int n = nums.size();
    vector<int> dp(n + 2, 0);

    for (int i = 0; i < n; ++i) {
        dp[i + 2] = max(dp[i + 1], dp[i] + nums[i]);
    }

    return dp[n + 1];
}
```

```python
def calculate_score(nums):
    n = len(nums)
    dp = [0] * (n + 2)

    for i in range(n):
        dp[i + 2] = max(dp[i + 1], dp[i] + nums[i])

    return dp[n + 1]
```


```python
def isValidMove(i, j, k, n):
    return (i + 1 < n and j + 2 < n and k == n * (i + 1) + (j + 2)) or \
           (i + 1 < n and j - 2 >= 0 and k == n * (i + 1) + (j - 2)) or \
           (i + 2 < n and j + 1 < n and k == n * (i + 2) + (j + 1)) or \
           (i + 2 < n and j - 1 >= 0 and k == n * (i + 2) + (j - 1))

def validPath(grid):
    n = len(grid)
    for i in range(n):
        for j in range(n):
            k = grid[i][j]
            if k != n * n - 1 and not isValidMove(i, j, k + 1, n):
                return False
    return 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 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

```cpp
bool isValidMove(int i, int j, int k, int n) {
    return (i + 1 < n && j + 2 < n && k == n * (i + 1) + (j + 2)) ||
           (i + 1 < n && j - 2 >= 0 && k == n * (i + 1) + (j - 2)) ||
           (i + 2 < n && j + 1 < n && k == n * (i + 2) + (j + 1)) ||
           (i + 2 < n && j - 1 >= 0 && k == n * (i + 2) + (j - 1));
}

bool validPath(vector<vector<int>>& grid) {
    int n = grid.size();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int k = grid[i][j];
            if (k != n * n - 1 && !isValidMove(i, j, k + 1, n)) {
                return false;
            }
        }
    }
    return true;
}
```


```python
def countBeautifulSubsets(nums, k):
    nums.sort()
    ans = 0
    dp = [1] * len(nums)
    for i in range(len(nums)):
        l = r = 0
        for j in range(i):
            while l < j and nums[j] - nums[l] >= k:
                l += 1
            while r + 1 < j and nums[r + 1] - nums[j] < k:
                r += 1
            dp[j] -= dp[l - 1] if l <= r else 0
            dp[j] += dp[j - 1] + 1
            ans += dp[j]
    return ans
```

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

int countBeautifulSubsets(vector<int>& nums, int k) {
    sort(nums.begin(), nums.end());
    int ans = 0;
    vector<int> dp(nums.size(), 1);
    for (int i = 0; i < nums.size(); i++) {
        for (int j = 0, l = 0, r = -1; j < i; j++) {
            while (l < j && nums[j] - nums[l] >= k) l++;
            while (r + 1 < j && nums[r + 1] - nums[j] < k) r++;
            if (l <= r) dp[j] -= dp[l - 1];
            dp[j] += dp[j - 1] + 1;
            ans += dp[j];
        }
    }
    return ans;
}
```


```python
def maximum_mex(nums: List[int], value: int) -> int:
    st = set(nums)

    for i in range(100001):
        if i not in st:
            st.add(i + value)

    mex = 0
    while mex in st:
        mex += 1

    return mex
```

```java
int maximum_mex(int[] nums, int value) {
    HashSet<Integer> st = new HashSet<>();

    for (int num : nums)
        st.add(num);

    for (int i = 0; i <= 100000; i++) {
        if (!st.contains(i))
            st.add(i + value);
    }

    int mex = 0;
    while (st.contains(mex))
        mex++;

    return mex;
}
```


```java
public int minOperations(int[] nums) {
    int minPrefix = 0;
    int prefix = 0;
    for (int num : nums) {
        prefix += num;
        minPrefix = Math.min(minPrefix, prefix);
    }
    return minPrefix < 0 ? -minPrefix : 0;
}
```

```python
def min_operations(nums):
    min_prefix = 0
    prefix = 0
    for num in nums:
        prefix += num
        min_prefix = min(min_prefix, prefix)
    return -min_prefix if min_prefix < 0 else 0
```


```cpp
#include <vector>

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

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

```java
public boolean strictlyIncreasingArray(int[] nums) {
    for (int i = 0; i < nums.length - 1; ++i) {
        nums[i] -= i;
        if (nums[i] >= nums[i + 1]) {
            return false;
        }
    }
    return true;
}
```


```python
from typing import List

def min_operations(nums: List[int], queries: List[int]) -> List[int]:
    answer = []
    for query in queries:
        operations = 0
        for num in nums:
            operations += abs(num - query)
        answer.append(operations)
    return answer
```

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

vector<int> min_operations(vector<int>& nums, vector<int>& queries) {
    vector<int> answer;
    for (int query : queries) {
        int operations = 0;
        for (int num : nums) {
            operations += abs(num - query);
        }
        answer.push_back(operations);
    }
    return answer;
}
```


```cpp
#include <vector>
#include <utility>

using std::vector;
using std::pair;

pair<int, int> dfs(const vector<vector<int>>& adj, const vector<int>& coins, int node, int parent) {
    int sum = coins[node], distance = 0;
    for (int neighbor : adj[node]) {
        if (neighbor != parent) {
            auto result = dfs(adj, coins, neighbor, node);
            sum += result.first;
            distance += 2 * result.first + result.second;
        }
    }
    return {sum, distance};
}

int minEdgesToCollectCoins(const vector<int>& coins, const vector<vector<int>>& edges) {
    int n = coins.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]);
    }
    return dfs(adj, coins, 0, -1).second / 2;
}
```

```java
import java.util.*;

public int minEdgesToCollectCoins(int[] coins, int[][] edges) {
    int n = coins.length;
    List<List<Integer>> adj = new ArrayList<>();
    for (int i = 0; i < n; i++) {
        adj.add(new ArrayList<>());
    }
    for (int[] edge : edges) {
        adj.get(edge[0]).add(edge[1]);
        adj.get(edge[1]).add(edge[0]);
    }
    return dfs(adj, coins, 0, -1)[1] / 2;
}

private int[] dfs(List<List<Integer>> adj, int[] coins, int node, int parent) {
    int sum = coins[node], distance = 0;
    for (int neighbor : adj.get(node)) {
        if (neighbor != parent) {
            int[] result = dfs(adj, coins, neighbor, node);
            sum += result[0];
            distance += 2 * result[0] + result[1];
        }
    }
    return new int[] {sum, distance};
}
```


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

int minTimeToEatGrains(std::vector<int>& hens, std::vector<int>& grains) {
    std::sort(hens.begin(), hens.end());
    std::sort(grains.begin(), grains.end());
    int left = 0, right = 1e9;

    while (left < right) {
        int mid = left + (right - left) / 2;
        bool can_eat = true;
        int i = 0;

        for (int grain : grains) {
            if (i >= hens.size()) {
                can_eat = false;
                break;
            }

            while (i < hens.size() && hens[i] < grain - mid) {
                ++i;
            }

            if (i >= hens.size() || hens[i] > grain + mid) {
                can_eat = false;
                break;
            }

            ++i;
        }

        if (can_eat) {
            right = mid;
        } else {
            left = mid + 1;
        }
    }

    return left;
}
```

```python
def min_time_to_eat_grains(hens, grains):
    hens.sort()
    grains.sort()
    left, right = 0, 10**9

    while left < right:
        mid = left + (right - left) // 2
        can_eat = True
        i = 0

        for grain in grains:
            if i >= len(hens):
                can_eat = False
                break

            while i < len(hens) and hens[i] < grain - mid:
                i += 1

            if i >= len(hens) or hens[i] > grain + mid:
                can_eat = False
                break

            i += 1

        if can_eat:
            right = mid
        else:
            left = mid + 1

    return left
```


```python
def smallest_number_with_at_least_one_digit_from_each_array(nums1, nums2):
    min1 = min(nums1)
    min2 = min(nums2)
    for num1 in nums1:
        for num2 in nums2:
            if num1 == num2:
                return num1
    return min1 * 10 + min2
```

```cpp
int smallestNumberWithAtLeastOneDigitFromEachArray(vector<int>& nums1, vector<int>& nums2) {
    int min1 = *min_element(nums1.begin(), nums1.end());
    int min2 = *min_element(nums2.begin(), nums2.end());
    for (int num1 : nums1) {
        for (int num2 : nums2) {
            if (num1 == num2) {
                return num1;
            }
        }
    }
    return min1 * 10 + min2;
}
```


```cpp
int minOperations(vector<int>& arr, int k) {
    int n = arr.size(), res = INT_MAX;
    vector<int> prefix(n + 1);

    for (int i = 1; i <= n; i++) {
        prefix[i] = prefix[i - 1] + arr[i - 1];
    }

    for (int i = 1; i <= n - k + 1; i++) {
        int target = (prefix[i - 1] + prefix[n] - prefix[i + k - 1] + n / k - 1) / (n / k);
        int curr_cost = 0;
        for (int j = i; j < i + k; j++) {
            curr_cost += abs(arr[j - 1] - target);
        }
        res = min(res, curr_cost);
    }
    return res;
}
```

```java
public int minOperations(int[] arr, int k) {
    int n = arr.length, res = Integer.MAX_VALUE;
    int[] prefix = new int[n + 1];

    for (int i = 1; i <= n; i++) {
        prefix[i] = prefix[i - 1] + arr[i - 1];
    }

    for (int i = 1; i <= n - k + 1; i++) {
        int target = (prefix[i - 1] + prefix[n] - prefix[i + k - 1] + n / k - 1) / (n / k);
        int curr_cost = 0;
        for (int j = i; j < i + k; j++) {
            curr_cost += Math.abs(arr[j - 1] - target);
        }
        res = Math.min(res, curr_cost);
    }
    return res;
}
```


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

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

    int shortestCycle = n + 1;
    for (int start = 0; start < n; ++start) {
        int[] dist = new int[n];
        for (int i = 0; i < n; ++i) {
            dist[i] = n + 1;
        }
        dist[start] = 0;
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(start);

        while (!queue.isEmpty()) {
            int cur = queue.poll();
            for (int neigh : graph.get(cur)) {
                if (dist[neigh] == n + 1) {
                    dist[neigh] = dist[cur] + 1;
                    queue.offer(neigh);
                } else if (dist[neigh] >= dist[cur] - 1) {
                    shortestCycle = Math.min(shortestCycle, dist[cur] + dist[neigh] + 1);
                }
            }
        }
    }

    return shortestCycle == n + 1 ? -1 : shortestCycle;
}
```

```python
from collections import deque

def shortest_cycle_length(n, edges):
    graph = [[] for _ in range(n)]
    for u, v in edges:
        graph[u].append(v)
        graph[v].append(u)

    shortest_cycle = n + 1
    for start in range(n):
        dist = [n + 1] * n
        dist[start] = 0
        queue = deque([start])

        while queue:
            cur = queue.popleft()
            for neigh in graph[cur]:
                if dist[neigh] == n + 1:
                    dist[neigh] = dist[cur] + 1
                    queue.append(neigh)
                elif dist[neigh] >= dist[cur] - 1:
                    shortest_cycle = min(shortest_cycle, dist[cur] + dist[neigh] + 1)

    return -1 if shortest_cycle == n + 1 else shortest_cycle
```


```python
def reach_position(n, p, banned, k):
    banned_positions = set(banned)
    ans = [0] * n

    for i in range(n):
        if i in banned_positions or i == p:
            ans[i] = -1
            continue

        an = abs(p - i) // k
        if abs(p - i) % k == 0 and (an & 1) == (((n - 1) & 1) ^ (k & 1)):
            steps = an
        else:
            steps = -1

        ans[i] = steps

    ans[p] = 0
    return ans
```

```cpp
#include <vector>
#include <set>

std::vector<int> reachPosition(int n, int p, std::vector<int> &banned, int k) {
    std::set<int> banned_positions(banned.begin(), banned.end());
    std::vector<int> ans(n, 0);

    for (int i = 0; i < n; ++i) {
        if (banned_positions.find(i) != banned_positions.end() || i == p) {
            ans[i] = -1;
            continue;
        }

        int steps = 0;
        int an = abs(p - i) / k;
        if ((abs(p - i) % k == 0) && ((an & 1) == (((n - 1) & 1) ^ (k & 1)))) {
            steps = an;
        }
        else {
            steps = -1;
        }

        ans[i] = steps;
    }

    ans[p] = 0;
    return ans;
}
```