# Minimize Result by Adding Parentheses to Expression

- slug: minimize-result-by-adding-parentheses-to-expression
- difficulty: Medium

You are given a **0-indexed** string `expression` of the form `"+ "` where and represent positive integers.

Add a pair of parentheses to `expression` such that after the addition of parentheses, `expression` is a **valid** mathematical expression and evaluates to the **smallest** possible value. The left parenthesis **must** be added to the left of `'+'` and the right parenthesis **must** be added to the right of `'+'`.

Return `expression` _after adding a pair of parentheses such that_ `expression` _evaluates to the **smallest** possible value._ If there are multiple answers that yield the same result, return any of them.

The input has been generated such that the original value of `expression`, and the value of `expression` after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.

**Example 1:**

**Input:** expression =  "247+38 "
**Output:**  "2(47+38) "
**Explanation:** The `expression` evaluates to 2 \* (47 + 38) = 2 \* 85 = 170.
Note that  "2(4)7+38 " is invalid because the right parenthesis must be to the right of the `'+'`.
It can be shown that 170 is the smallest possible value.

**Example 2:**

**Input:** expression =  "12+34 "
**Output:**  "1(2+3)4 "
**Explanation:** The expression evaluates to 1 \* (2 + 3) \* 4 = 1 \* 5 \* 4 = 20.

**Example 3:**

**Input:** expression =  "999+999 "
**Output:**  "(999+999) "
**Explanation:** The `expression` evaluates to 999 + 999 = 1998.

**Constraints:**

*   `3 <= expression.length <= 10`
*   `expression` consists of digits from `'1'` to `'9'` and `'+'`.
*   `expression` starts and ends with digits.
*   `expression` contains exactly one `'+'`.
*   The original value of `expression`, and the value of `expression` after adding any pair of parentheses that meets the requirements fits within a signed 32-bit integer.

## A solution in Java

```java
public String addSpaces(String s, int[] spaces) {
    StringBuilder result = new StringBuilder();
    int j = 0;
    for (int i = 0; i < s.length(); i++) {
        while (j < spaces.length && i == spaces[j]) {
            result.append(' ');
            j++;
        }
        result.append(s.charAt(i));
    }
    return result.toString();
}
```
The algorithm initializes an empty result string (or StringBuilder in Java for better performance). We iterate through the input string and for each character, we use a `while` loop to check if the current index `i` is in the `spaces` array (by comparing `i` to `spaces[j]` where `j` is initialized at 0). If we need to add a space before the current character, we append a space to the result string and increment `j`. The current character at index `i` of the input string is then appended to the result string. The final result string is returned after iterating through the input string. The algorithm's time complexity is O(n) where n is the length of the input string, as each character in the input string is visited once.

## A solution in C++

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

string addSpaces(const string& s, const vector<int>& spaces) {
    string result;
    int j = 0;
    for (int i = 0; i < s.size(); i++) {
        while (j < spaces.size() && i == spaces[j]) {
            result += ' ';
            j++;
        }
        result += s[i];
    }
    return result;
}
```
The algorithm initializes an empty result string (or StringBuilder in Java for better performance). We iterate through the input string and for each character, we use a `while` loop to check if the current index `i` is in the `spaces` array (by comparing `i` to `spaces[j]` where `j` is initialized at 0). If we need to add a space before the current character, we append a space to the result string and increment `j`. The current character at index `i` of the input string is then appended to the result string. The final result string is returned after iterating through the input string. The algorithm's time complexity is O(n) where n is the length of the input string, as each character in the input string is visited once.

## A solution in Python

```python
def add_spaces(s: str, spaces: List[int]) -> str:
    result = []
    j = 0
    for i, c in enumerate(s):
        while j < len(spaces) and i == spaces[j]:
            result.append(' ')
            j += 1
        result.append(c)
    return ''.join(result)
```
The algorithm initializes an empty result string (or StringBuilder in Java for better performance). We iterate through the input string and for each character, we use a `while` loop to check if the current index `i` is in the `spaces` array (by comparing `i` to `spaces[j]` where `j` is initialized at 0). If we need to add a space before the current character, we append a space to the result string and increment `j`. The current character at index `i` of the input string is then appended to the result string. The final result string is returned after iterating through the input string. The algorithm's time complexity is O(n) where n is the length of the input string, as each character in the input string is visited once.

## A solution in Javascript

```javascript
function addSpaces(s, spaces) {
    let result = "";
    let j = 0;
    for (let i = 0; i < s.length; i++) {
        while (j < spaces.length && i === spaces[j]) {
            result += ' ';
            j++;
        }
        result += s[i];
    }
    return result;
}
```
The algorithm initializes an empty result string (or StringBuilder in Java for better performance). We iterate through the input string and for each character, we use a `while` loop to check if the current index `i` is in the `spaces` array (by comparing `i` to `spaces[j]` where `j` is initialized at 0). If we need to add a space before the current character, we append a space to the result string and increment `j`. The current character at index `i` of the input string is then appended to the result string. The final result string is returned after iterating through the input string. The algorithm's time complexity is O(n) where n is the length of the input string, as each character in the input string is visited once.


# Maximum Product After K Increments

- slug: maximum-product-after-k-increments
- difficulty: Medium

You are given an array of non-negative integers `nums` and an integer `k`. In one operation, you may choose **any** element from `nums` and **increment** it by `1`.

Return _the **maximum** **product** of_ `nums` _after **at most**_ `k` _operations._ Since the answer may be very large, return it **modulo** `109 + 7`. Note that you should maximize the product before taking the modulo.

**Example 1:**

**Input:** nums = \[0,4\], k = 5
**Output:** 20
**Explanation:** Increment the first number 5 times.
Now nums = \[5, 4\], with a product of 5 \* 4 = 20.
It can be shown that 20 is maximum product possible, so we return 20.
Note that there may be other ways to increment nums to have the maximum product.

**Example 2:**

**Input:** nums = \[6,3,3,2\], k = 2
**Output:** 216
**Explanation:** Increment the second number 1 time and increment the fourth number 1 time.
Now nums = \[6, 4, 3, 3\], with a product of 6 \* 4 \* 3 \* 3 = 216.
It can be shown that 216 is maximum product possible, so we return 216.
Note that there may be other ways to increment nums to have the maximum product.

**Constraints:**

*   `1 <= nums.length, k <= 105`
*   `0 <= nums[i] <= 106`

## A solution in Java

```java
public int smoothDescentPeriods(int[] prices) {
    int count = 0;
    for (int i = 1; i < prices.length; ++i) {
        if (prices[i] == prices[i - 1] - 1) {
            while (i < prices.length && prices[i] == prices[i - 1] - 1) {
                i++;
            }
            count++;
        }
    }
    return count;
}
```
The algorithm maintains a count of smooth descent periods. We iterate through the `prices` array starting from the second element (index 1). If we find that the current price is less than the previous price by exactly 1, we enter the "smooth descent" mode by continuously checking the next elements as long as the price keeps decreasing by exactly 1. Once this condition is no longer true or we reach the end of the `prices` array, we increment the count of smooth descent periods and continue searching from the next unchecked index. Finally, we return the count of smooth descent periods.

This algorithm has a time complexity of O(n), where n is the number of elements in the `prices` array. The reason it is not O(n^2), despite having nested loops, is that the nested loop's index `i` is never reset, so each element is examined at most twice.

## A solution in C++

```cpp
#include <vector>

int smoothDescentPeriods(std::vector<int>& prices) {
    int count = 0;
    for (int i = 1; i < prices.size(); ++i) {
        if (prices[i] == prices[i - 1] - 1) {
            while (i < prices.size() && prices[i] == prices[i - 1] - 1) {
                i++;
            }
            count++;
        }
    }
    return count;
}
```
The algorithm maintains a count of smooth descent periods. We iterate through the `prices` array starting from the second element (index 1). If we find that the current price is less than the previous price by exactly 1, we enter the "smooth descent" mode by continuously checking the next elements as long as the price keeps decreasing by exactly 1. Once this condition is no longer true or we reach the end of the `prices` array, we increment the count of smooth descent periods and continue searching from the next unchecked index. Finally, we return the count of smooth descent periods.

This algorithm has a time complexity of O(n), where n is the number of elements in the `prices` array. The reason it is not O(n^2), despite having nested loops, is that the nested loop's index `i` is never reset, so each element is examined at most twice.

## A solution in Python

```python
def smooth_descent_periods(prices):
    count = 0
    i = 1
    while i < len(prices):
        if prices[i] == prices[i - 1] - 1:
            while i < len(prices) and prices[i] == prices[i - 1] - 1:
                i += 1
            count += 1
        else:
            i += 1
    return count
```
The algorithm maintains a count of smooth descent periods. We iterate through the `prices` array starting from the second element (index 1). If we find that the current price is less than the previous price by exactly 1, we enter the "smooth descent" mode by continuously checking the next elements as long as the price keeps decreasing by exactly 1. Once this condition is no longer true or we reach the end of the `prices` array, we increment the count of smooth descent periods and continue searching from the next unchecked index. Finally, we return the count of smooth descent periods.

This algorithm has a time complexity of O(n), where n is the number of elements in the `prices` array. The reason it is not O(n^2), despite having nested loops, is that the nested loop's index `i` is never reset, so each element is examined at most twice.

## A solution in Javascript

```javascript
function smoothDescentPeriods(prices) {
    let count = 0;
    for (let i = 1; i < prices.length; ++i) {
        if (prices[i] === prices[i - 1] - 1) {
            while (i < prices.length && prices[i] === prices[i - 1] - 1) {
                i++;
            }
            count++;
        }
    }
    return count;
}
```
The algorithm maintains a count of smooth descent periods. We iterate through the `prices` array starting from the second element (index 1). If we find that the current price is less than the previous price by exactly 1, we enter the "smooth descent" mode by continuously checking the next elements as long as the price keeps decreasing by exactly 1. Once this condition is no longer true or we reach the end of the `prices` array, we increment the count of smooth descent periods and continue searching from the next unchecked index. Finally, we return the count of smooth descent periods.

This algorithm has a time complexity of O(n), where n is the number of elements in the `prices` array. The reason it is not O(n^2), despite having nested loops, is that the nested loop's index `i` is never reset, so each element is examined at most twice.


# Maximum Total Beauty of the Gardens

- slug: maximum-total-beauty-of-the-gardens
- difficulty: Hard

Alice is a caretaker of `n` gardens and she wants to plant flowers to maximize the total beauty of all her gardens.

You are given a **0-indexed** integer array `flowers` of size `n`, where `flowers[i]` is the number of flowers already planted in the `ith` garden. Flowers that are already planted **cannot** be removed. You are then given another integer `newFlowers`, which is the **maximum** number of flowers that Alice can additionally plant. You are also given the integers `target`, `full`, and `partial`.

A garden is considered **complete** if it has **at least** `target` flowers. The **total beauty** of the gardens is then determined as the **sum** of the following:

*   The number of **complete** gardens multiplied by `full`.
*   The **minimum** number of flowers in any of the **incomplete** gardens multiplied by `partial`. If there are no incomplete gardens, then this value will be `0`.

Return _the **maximum** total beauty that Alice can obtain after planting at most_ `newFlowers` _flowers._

**Example 1:**

**Input:** flowers = \[1,3,1,1\], newFlowers = 7, target = 6, full = 12, partial = 1
**Output:** 14
**Explanation:** Alice can plant
- 2 flowers in the 0th garden
- 3 flowers in the 1st garden
- 1 flower in the 2nd garden
- 1 flower in the 3rd garden
The gardens will then be \[3,6,2,2\]. She planted a total of 2 + 3 + 1 + 1 = 7 flowers.
There is 1 garden that is complete.
The minimum number of flowers in the incomplete gardens is 2.
Thus, the total beauty is 1 \* 12 + 2 \* 1 = 12 + 2 = 14.
No other way of planting flowers can obtain a total beauty higher than 14.

**Example 2:**

**Input:** flowers = \[2,4,5,3\], newFlowers = 10, target = 5, full = 2, partial = 6
**Output:** 30
**Explanation:** Alice can plant
- 3 flowers in the 0th garden
- 0 flowers in the 1st garden
- 0 flowers in the 2nd garden
- 2 flowers in the 3rd garden
The gardens will then be \[5,4,5,5\]. She planted a total of 3 + 0 + 0 + 2 = 5 flowers.
There are 3 gardens that are complete.
The minimum number of flowers in the incomplete gardens is 4.
Thus, the total beauty is 3 \* 2 + 4 \* 6 = 6 + 24 = 30.
No other way of planting flowers can obtain a total beauty higher than 30.
Note that Alice could make all the gardens complete but in this case, she would obtain a lower total beauty.

**Constraints:**

*   `1 <= flowers.length <= 105`
*   `1 <= flowers[i], target <= 105`
*   `1 <= newFlowers <= 1010`
*   `1 <= full, partial <= 105`

## A solution in Java

```java
int minOperationsToKIncreasing(int[] arr, int k) {
    int operations = 0;
    for (int i = k; i < arr.length; i++) {
        if (arr[i] <= arr[i - k]) {
            operations += (arr[i - k] - arr[i] + 1);
            arr[i] = arr[i - k] + 1;
        }
    }
    return operations;
}
```
To make the array K-increasing, we iterate through the array, starting from index k.
For each index i, if the condition arr[i-k] > arr[i] does not hold, it means that we need to change the value of arr[i] to make it K-increasing. So, we calculate the difference between the elements arr[i-k] and arr[i], add 1 to the result, and then update the value of arr[i] by adding the calculated difference to arr[i-k]. We also increment our operations counter by the same difference value.
This will ensure that the array is K-increasing and keeps track of the minimum number of operations required to change the array. We continue iterating through the array until the last element and return the total number of operations in the end.

## A solution in C++

```cpp
int min_operations_to_K_increasing(vector<int>& arr, int k) {
    int operations = 0;
    for (int i = k; i < arr.size(); i++) {
        if (arr[i] <= arr[i - k]) {
            operations += (arr[i - k] - arr[i] + 1);
            arr[i] = arr[i - k] + 1;
        }
    }
    return operations;
}
```
To make the array K-increasing, we iterate through the array, starting from index k.
For each index i, if the condition arr[i-k] > arr[i] does not hold, it means that we need to change the value of arr[i] to make it K-increasing. So, we calculate the difference between the elements arr[i-k] and arr[i], add 1 to the result, and then update the value of arr[i] by adding the calculated difference to arr[i-k]. We also increment our operations counter by the same difference value.
This will ensure that the array is K-increasing and keeps track of the minimum number of operations required to change the array. We continue iterating through the array until the last element and return the total number of operations in the end.

## A solution in Python

```python
def min_operations_to_K_increasing(arr, k):
    operations = 0
    for i in range(k, len(arr)):
        if arr[i] <= arr[i - k]:
            operations += (arr[i - k] - arr[i] + 1)
            arr[i] = arr[i - k] + 1
    return operations
```
To make the array K-increasing, we iterate through the array, starting from index k.
For each index i, if the condition arr[i-k] > arr[i] does not hold, it means that we need to change the value of arr[i] to make it K-increasing. So, we calculate the difference between the elements arr[i-k] and arr[i], add 1 to the result, and then update the value of arr[i] by adding the calculated difference to arr[i-k]. We also increment our operations counter by the same difference value.
This will ensure that the array is K-increasing and keeps track of the minimum number of operations required to change the array. We continue iterating through the array until the last element and return the total number of operations in the end.

## A solution in Javascript

```javascript
function minOperationsToKIncreasing(arr, k) {
    let operations = 0;
    for (let i = k; i < arr.length; i++) {
        if (arr[i] <= arr[i - k]) {
            operations += (arr[i - k] - arr[i] + 1);
            arr[i] = arr[i - k] + 1;
        }
    }
    return operations;
}
```
To make the array K-increasing, we iterate through the array, starting from index k.
For each index i, if the condition arr[i-k] > arr[i] does not hold, it means that we need to change the value of arr[i] to make it K-increasing. So, we calculate the difference between the elements arr[i-k] and arr[i], add 1 to the result, and then update the value of arr[i] by adding the calculated difference to arr[i-k]. We also increment our operations counter by the same difference value.
This will ensure that the array is K-increasing and keeps track of the minimum number of operations required to change the array. We continue iterating through the array until the last element and return the total number of operations in the end.


# Add Two Integers

- slug: add-two-integers
- difficulty: Easy

Given two integers `num1` and `num2`, return _the **sum** of the two integers_.

**Example 1:**

**Input:** num1 = 12, num2 = 5
**Output:** 17
**Explanation:** num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.

**Example 2:**

**Input:** num1 = -10, num2 = 4
**Output:** -6
**Explanation:** num1 + num2 = -6, so -6 is returned.

**Constraints:**

*   `-100 <= num1, num2 <= 100`

## A solution in Java

```java
public String capitalizeTitle(String title) {
    StringBuilder result = new StringBuilder();
    boolean newWord = true;

    for (int i = 0; i < title.length(); ++i) {
        char character = title.charAt(i);
        if (newWord && Character.isLetter(character)) {
            result.append(Character.toUpperCase(character));
            newWord = false;
        } else if (character == ' ') {
            result.append(character);
            newWord = true;
        } else {
            result.append(Character.toLowerCase(character));
        }
    }
    return result.toString();
}
```
The algorithm loops through each character of the string `title`. If it encounters a new word edge (either beginning of the title or previous character was a space), the current character is capitalized. In all other cases, the character is converted to lower case. In Python, we use the built-in `.capitalize()` method to capitalize each word in the title. We split the string into words, apply the capitalize method on each word, and join the words by spaces.

## A solution in C++

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

string capitalizeTitle(string title) {
    bool newWord = true;
    for (int i = 0; i < title.length(); ++i) {
        if (newWord && isalpha(title[i])) {
            title[i] = toupper(title[i]);
            newWord = false;
        } else if (title[i] == ' ') {
            newWord = true;
        } else {
            title[i] = tolower(title[i]);
        }
    }
    return title;
}
```
The algorithm loops through each character of the string `title`. If it encounters a new word edge (either beginning of the title or previous character was a space), the current character is capitalized. In all other cases, the character is converted to lower case. In Python, we use the built-in `.capitalize()` method to capitalize each word in the title. We split the string into words, apply the capitalize method on each word, and join the words by spaces.

## A solution in Python

```python
def capitalize_title(title):
    return ' '.join([word.capitalize() for word in title.split(' ')])
```
The algorithm loops through each character of the string `title`. If it encounters a new word edge (either beginning of the title or previous character was a space), the current character is capitalized. In all other cases, the character is converted to lower case. In Python, we use the built-in `.capitalize()` method to capitalize each word in the title. We split the string into words, apply the capitalize method on each word, and join the words by spaces.

## A solution in Javascript

```javascript
function capitalizeTitle(title) {
    const words = title.split(' ');

    for (let i = 0; i < words.length; i++) {
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1).toLowerCase();
    }

    return words.join(' ');
}
```
The algorithm loops through each character of the string `title`. If it encounters a new word edge (either beginning of the title or previous character was a space), the current character is capitalized. In all other cases, the character is converted to lower case. In Python, we use the built-in `.capitalize()` method to capitalize each word in the title. We split the string into words, apply the capitalize method on each word, and join the words by spaces.


# Root Equals Sum of Children

- slug: root-equals-sum-of-children
- difficulty: Easy

You are given the `root` of a **binary tree** that consists of exactly `3` nodes: the root, its left child, and its right child.

Return `true` _if the value of the root is equal to the **sum** of the values of its two children, or_ `false` _otherwise_.

**Example 1:**

**Input:** root = \[10,4,6\]
**Output:** true
**Explanation:** The values of the root, its left child, and its right child are 10, 4, and 6, respectively.
10 is equal to 4 + 6, so we return true.

**Example 2:**

**Input:** root = \[5,3,1\]
**Output:** false
**Explanation:** The values of the root, its left child, and its right child are 5, 3, and 1, respectively.
5 is not equal to 3 + 1, so we return false.

**Constraints:**

*   The tree consists only of the root, its left child, and its right child.
*   `-100 <= Node.val <= 100`

## A solution in Java

```java
public int maxTwinSum(ListNode head) {
    int sum = 0, max_sum = 0, i = 0;
    ListNode slow = head, fast = head;

    while (fast != null && fast.next != null) {
        fast = fast.next.next;
        i++;
    }

    for (int j = 0; j < i; j++) {
        sum = slow.val + fast.val;
        max_sum = Math.max(max_sum, sum);
        slow = slow.next;
        fast = fast.prev;
    }

    return max_sum;
}
```
The algorithm uses two pointers (slow and fast) to simultaneously traverse the linked list. The slow pointer moves forward one step at a time, while the fast pointer moves two steps at a time. This allows the fast_pointer to reach the end of the list when the slow_pointer is exactly halfway through the list.

After reaching the middle, the function iterates through the first half of the list, calculating the twin sum of each node with its twin (which is being referenced by the fast pointer) and storing the maximum value. To do this, it advances the slow pointer one step at a time, while the fast pointer moves one step back. At each step, it calculates the sum of the values at the current positions of the slow and fast pointers, updating the maximum twin sum if a higher sum is found.

Finally, after traversing half of the linked list, the function returns the maximum twin sum.

## A solution in C++

```cpp
int maxTwinSum(ListNode* head) {
    int sum = 0, max_sum = 0, i = 0;
    ListNode* slow = head, *fast = head;

    while (fast && fast->next) {
        fast = fast->next->next;
        i++;
    }

    for (int j = 0; j < i; j++) {
        sum = slow->val + fast->val;
        max_sum = max(max_sum, sum);
        slow = slow->next;
        fast = fast->prev;
    }

    return max_sum;
}
```
The algorithm uses two pointers (slow and fast) to simultaneously traverse the linked list. The slow pointer moves forward one step at a time, while the fast pointer moves two steps at a time. This allows the fast_pointer to reach the end of the list when the slow_pointer is exactly halfway through the list.

After reaching the middle, the function iterates through the first half of the list, calculating the twin sum of each node with its twin (which is being referenced by the fast pointer) and storing the maximum value. To do this, it advances the slow pointer one step at a time, while the fast pointer moves one step back. At each step, it calculates the sum of the values at the current positions of the slow and fast pointers, updating the maximum twin sum if a higher sum is found.

Finally, after traversing half of the linked list, the function returns the maximum twin sum.

## A solution in Python

```python
def max_twin_sum(head):
    sum = 0
    max_sum = 0
    i = 0
    slow = head
    fast = head

    while fast and fast.next:
        fast = fast.next.next
        i += 1

    for j in range(i):
        sum = slow.val + fast.val
        max_sum = max(max_sum, sum)
        slow = slow.next
        fast = fast.prev

    return max_sum
```
The algorithm uses two pointers (slow and fast) to simultaneously traverse the linked list. The slow pointer moves forward one step at a time, while the fast pointer moves two steps at a time. This allows the fast_pointer to reach the end of the list when the slow_pointer is exactly halfway through the list.

After reaching the middle, the function iterates through the first half of the list, calculating the twin sum of each node with its twin (which is being referenced by the fast pointer) and storing the maximum value. To do this, it advances the slow pointer one step at a time, while the fast pointer moves one step back. At each step, it calculates the sum of the values at the current positions of the slow and fast pointers, updating the maximum twin sum if a higher sum is found.

Finally, after traversing half of the linked list, the function returns the maximum twin sum.

## A solution in Javascript

```javascript
function maxTwinSum(head) {
    let sum = 0, max_sum = 0, i = 0;
    let slow = head, fast = head;

    while (fast && fast.next) {
        fast = fast.next.next;
        i++;
    }

    for (let j = 0; j < i; j++) {
        sum = slow.val + fast.val;
        max_sum = Math.max(max_sum, sum);
        slow = slow.next;
        fast = fast.prev;
    }

    return max_sum;
}
```
The algorithm uses two pointers (slow and fast) to simultaneously traverse the linked list. The slow pointer moves forward one step at a time, while the fast pointer moves two steps at a time. This allows the fast_pointer to reach the end of the list when the slow_pointer is exactly halfway through the list.

After reaching the middle, the function iterates through the first half of the list, calculating the twin sum of each node with its twin (which is being referenced by the fast pointer) and storing the maximum value. To do this, it advances the slow pointer one step at a time, while the fast pointer moves one step back. At each step, it calculates the sum of the values at the current positions of the slow and fast pointers, updating the maximum twin sum if a higher sum is found.

Finally, after traversing half of the linked list, the function returns the maximum twin sum.


# Count Positions on Street With Required Brightness

- slug: count-positions-on-street-with-required-brightness
- difficulty: Medium

You are given an integer `n`. A perfectly straight street is represented by a number line ranging from `0` to `n - 1`. You are given a 2D integer array `lights` representing the street lamp(s) on the street. Each `lights[i] = [positioni, rangei]` indicates that there is a street lamp at position `positioni` that lights up the area from `[max(0, positioni - rangei), min(n - 1, positioni + rangei)]` (**inclusive**).

The **brightness** of a position `p` is defined as the number of street lamps that light up the position `p`. You are given a **0-indexed** integer array `requirement` of size `n` where `requirement[i]` is the minimum **brightness** of the `ith` position on the street.

Return _the number of positions_ `i` _on the street between_ `0` _and_ `n - 1` _that have a **brightness**_ _of **at least**_ `requirement[i]`_._

**Example 1:**

**Input:** n = 5, lights = \[\[0,1\],\[2,1\],\[3,2\]\], requirement = \[0,2,1,4,1\]
**Output:** 4
**Explanation:**
- The first street lamp lights up the area from \[max(0, 0 - 1), min(n - 1, 0 + 1)\] = \[0, 1\] (inclusive).
- The second street lamp lights up the area from \[max(0, 2 - 1), min(n - 1, 2 + 1)\] = \[1, 3\] (inclusive).
- The third street lamp lights up the area from \[max(0, 3 - 2), min(n - 1, 3 + 2)\] = \[1, 4\] (inclusive).

- Position 0 is covered by the first street lamp. It is covered by 1 street lamp which is greater than requirement\[0\].
- Position 1 is covered by the first, second, and third street lamps. It is covered by 3 street lamps which is greater than requirement\[1\].
- Position 2 is covered by the second and third street lamps. It is covered by 2 street lamps which is greater than requirement\[2\].
- Position 3 is covered by the second and third street lamps. It is covered by 2 street lamps which is less than requirement\[3\].
- Position 4 is covered by the third street lamp. It is covered by 1 street lamp which is equal to requirement\[4\].

Positions 0, 1, 2, and 4 meet the requirement so we return 4.

**Example 2:**

**Input:** n = 1, lights = \[\[0,1\]\], requirement = \[2\]
**Output:** 0
**Explanation:**
- The first street lamp lights up the area from \[max(0, 0 - 1), min(n - 1, 0 + 1)\] = \[0, 0\] (inclusive).
- Position 0 is covered by the first street lamp. It is covered by 1 street lamp which is less than requirement\[0\].
- We return 0 because no position meets their brightness requirement.

**Constraints:**

*   `1 <= n <= 105`
*   `1 <= lights.length <= 105`
*   `0 <= positioni < n`
*   `0 <= rangei <= 105`
*   `requirement.length == n`
*   `0 <= requirement[i] <= 105`

## A solution in Java

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

public int longestPalindrome(String[] words) {
    HashMap<Character, Integer> dict = new HashMap<>();
    int result = 0;
    boolean hasOdd = false;

    for (String word : words) {
        dict.put(word.charAt(0), dict.getOrDefault(word.charAt(0), 0) + 1);
        dict.put(word.charAt(1), dict.getOrDefault(word.charAt(1), 0) + 1);
    }

    for (Map.Entry<Character, Integer> entry : dict.entrySet()) {
        result += entry.getValue() / 2 * 2;
        hasOdd |= entry.getValue() % 2 == 1;
    }

    return result + (hasOdd ? 1 : 0);
}
```
1. Create an empty dictionary `dict` to store counts of characters.
2. Initialize `result` to 0 and set `has_odd` to false.
3. Iterate through the input `words` and count the occurrences of characters by updating the `dict`.
4. Iterate through the values of the `dict`. For each value, add the largest even number less than or equal to the value to `result`. If the current value is odd, set `has_odd` to true.
5. If `has_odd` is true, increment `result` by 1.
6. Return `result` as the length of the longest palindrome.

## A solution in C++

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

int longest_palindrome(std::vector<std::string>& words) {
    std::unordered_map<char, int> dict;
    int result = 0;
    bool has_odd = false;

    for (const auto& word : words) {
        dict[word[0]]++;
        dict[word[1]]++;
    }

    for (const auto& pair : dict) {
        result += pair.second / 2 * 2;
        has_odd |= pair.second % 2;
    }

    return result + has_odd;
}
```
1. Create an empty dictionary `dict` to store counts of characters.
2. Initialize `result` to 0 and set `has_odd` to false.
3. Iterate through the input `words` and count the occurrences of characters by updating the `dict`.
4. Iterate through the values of the `dict`. For each value, add the largest even number less than or equal to the value to `result`. If the current value is odd, set `has_odd` to true.
5. If `has_odd` is true, increment `result` by 1.
6. Return `result` as the length of the longest palindrome.

## A solution in Python

```python
def longest_palindrome(words):
    from collections import defaultdict
    dict = defaultdict(int)
    result = 0
    has_odd = False

    for word in words:
        dict[word[0]] += 1
        dict[word[1]] += 1

    for count in dict.values():
        result += count // 2 * 2
        has_odd |= count % 2

    return result + has_odd
```
1. Create an empty dictionary `dict` to store counts of characters.
2. Initialize `result` to 0 and set `has_odd` to false.
3. Iterate through the input `words` and count the occurrences of characters by updating the `dict`.
4. Iterate through the values of the `dict`. For each value, add the largest even number less than or equal to the value to `result`. If the current value is odd, set `has_odd` to true.
5. If `has_odd` is true, increment `result` by 1.
6. Return `result` as the length of the longest palindrome.

## A solution in Javascript

```javascript
function longestPalindrome(words) {
    let dict = {};
    let result = 0;
    let hasOdd = false;

    for (let word of words) {
        dict[word[0]] = (dict[word[0]] || 0) + 1;
        dict[word[1]] = (dict[word[1]] || 0) + 1;
    }

    for (let count of Object.values(dict)) {
        result += Math.floor(count / 2) * 2;
        hasOdd |= count % 2;
    }

    return result + (hasOdd ? 1 : 0);
}
```
1. Create an empty dictionary `dict` to store counts of characters.
2. Initialize `result` to 0 and set `has_odd` to false.
3. Iterate through the input `words` and count the occurrences of characters by updating the `dict`.
4. Iterate through the values of the `dict`. For each value, add the largest even number less than or equal to the value to `result`. If the current value is odd, set `has_odd` to true.
5. If `has_odd` is true, increment `result` by 1.
6. Return `result` as the length of the longest palindrome.


# Find Closest Number to Zero

- slug: find-closest-number-to-zero
- difficulty: Easy

Given an integer array `nums` of size `n`, return _the number with the value **closest** to_ `0` _in_ `nums`. If there are multiple answers, return _the number with the **largest** value_.

**Example 1:**

**Input:** nums = \[-4,-2,1,4,8\]
**Output:** 1
**Explanation:**
The distance from -4 to 0 is |-4| = 4.
The distance from -2 to 0 is |-2| = 2.
The distance from 1 to 0 is |1| = 1.
The distance from 4 to 0 is |4| = 4.
The distance from 8 to 0 is |8| = 8.
Thus, the closest number to 0 in the array is 1.

**Example 2:**

**Input:** nums = \[2,-1,1\]
**Output:** 1
**Explanation:** 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.

**Constraints:**

*   `1 <= n <= 1000`
*   `-105 <= nums[i] <= 105`

## A solution in Java

```java
import java.util.Arrays;

public int[] robotInstructions(int n, int[] startPos, String s) {
    int[] answer = new int[s.length()];

    for (int idx = 0; idx < s.length(); ++idx) {
        int row = startPos[0];
        int col = startPos[1];

        for (int i = idx; i < s.length(); ++i) {
            char move = s.charAt(i);
            if (move == 'L') --col;
            else if (move == 'R') ++col;
            else if (move == 'U') --row;
            else if (move == 'D') ++row;

            if (row < 0 || row >= n || col < 0 || col >= n) {
                break;
            }

            answer[idx]++;
        }
    }

    return answer;
}
```
This algorithm implements a nested loop. The outer loop iterates through each starting instruction index. In the inner loop, we execute the instructions while updating the position of the robot in terms of row and column. If a move will take the robot outside the grid, we break from the inner loop. If the robot hasn't exited the grid, we increase the number of instructions it has executed, which is stored in the answer array indexed by the starting instruction index.

The time complexity is O(m^2), where m is the length of the instructions string s. The space complexity is O(m), as we need to store the answer for each starting instruction index in an array.

## A solution in C++

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

std::vector<int> robotInstructions(int n, std::vector<int>& startPos, const std::string& s) {
    std::vector<int> answer(s.length(), 0);

    for (int idx = 0; idx < s.length(); ++idx) {
        int row = startPos[0];
        int col = startPos[1];

        for (int i = idx; i < s.length(); ++i) {
            if (s[i] == 'L') --col;
            else if (s[i] == 'R') ++col;
            else if (s[i] == 'U') --row;
            else if (s[i] == 'D') ++row;

            if (row < 0 || row >= n || col < 0 || col >= n) {
                break;
            }

            answer[idx]++;
        }
    }

    return answer;
}
```
This algorithm implements a nested loop. The outer loop iterates through each starting instruction index. In the inner loop, we execute the instructions while updating the position of the robot in terms of row and column. If a move will take the robot outside the grid, we break from the inner loop. If the robot hasn't exited the grid, we increase the number of instructions it has executed, which is stored in the answer array indexed by the starting instruction index.

The time complexity is O(m^2), where m is the length of the instructions string s. The space complexity is O(m), as we need to store the answer for each starting instruction index in an array.

## A solution in Python

```python
def robot_instructions(n: int, start_pos: list, s: str) -> list:
    answer = [0] * len(s)

    for idx in range(len(s)):
        row, col = start_pos

        for i in range(idx, len(s)):
            move = s[i]
            if move == 'L':
                col -= 1
            elif move == 'R':
                col += 1
            elif move == 'U':
                row -= 1
            elif move == 'D':
                row += 1

            if row < 0 or row >= n or col < 0 or col >= n:
                break

            answer[idx] += 1

    return answer
```
This algorithm implements a nested loop. The outer loop iterates through each starting instruction index. In the inner loop, we execute the instructions while updating the position of the robot in terms of row and column. If a move will take the robot outside the grid, we break from the inner loop. If the robot hasn't exited the grid, we increase the number of instructions it has executed, which is stored in the answer array indexed by the starting instruction index.

The time complexity is O(m^2), where m is the length of the instructions string s. The space complexity is O(m), as we need to store the answer for each starting instruction index in an array.

## A solution in Javascript

```javascript
function robotInstructions(n, startPos, s) {
    let answer = new Array(s.length).fill(0);

    for (let idx = 0; idx < s.length; ++idx) {
        let row = startPos[0];
        let col = startPos[1];

        for (let i = idx; i < s.length; ++i) {
            let move = s[i];
            if (move === 'L') --col;
            else if (move === 'R') ++col;
            else if (move === 'U') --row;
            else if (move === 'D') ++row;

            if (row < 0 || row >= n || col < 0 || col >= n) {
                break;
            }

            answer[idx]++;
        }
    }

    return answer;
}
```
This algorithm implements a nested loop. The outer loop iterates through each starting instruction index. In the inner loop, we execute the instructions while updating the position of the robot in terms of row and column. If a move will take the robot outside the grid, we break from the inner loop. If the robot hasn't exited the grid, we increase the number of instructions it has executed, which is stored in the answer array indexed by the starting instruction index.

The time complexity is O(m^2), where m is the length of the instructions string s. The space complexity is O(m), as we need to store the answer for each starting instruction index in an array.


# Number of Ways to Buy Pens and Pencils

- slug: number-of-ways-to-buy-pens-and-pencils
- difficulty: Medium

You are given an integer `total` indicating the amount of money you have. You are also given two integers `cost1` and `cost2` indicating the price of a pen and pencil respectively. You can spend **part or all** of your money to buy multiple quantities (or none) of each kind of writing utensil.

Return _the **number of distinct ways** you can buy some number of pens and pencils._

**Example 1:**

**Input:** total = 20, cost1 = 10, cost2 = 5
**Output:** 9
**Explanation:** The price of a pen is 10 and the price of a pencil is 5.
- If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils.
- If you buy 1 pen, you can buy 0, 1, or 2 pencils.
- If you buy 2 pens, you cannot buy any pencils.
The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.

**Example 2:**

**Input:** total = 5, cost1 = 10, cost2 = 10
**Output:** 1
**Explanation:** The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils.

**Constraints:**

*   `1 <= total, cost1, cost2 <= 106`

## A solution in Java

```java
import java.util.*;

class Solution {
    public int[] sumOfIntervals(int[] arr) {
        int n = arr.length;
        List<ArrayList<Integer>> indices = new ArrayList<>(101);
        for (int i = 0; i < 101; i++) {
            indices.add(new ArrayList<>());
        }
        int[] intervals = new int[n];

        for (int i = 0; i < n; ++i) {
            indices.get(arr[i]).add(i);
        }

        for (int i = 0; i < n; ++i) {
            for (int index : indices.get(arr[i])) {
                intervals[i] += Math.abs(index - i);
            }
        }

        return intervals;
    }
}
```
1. Store the indices of each element in arr in a separate data structure (in this case, a vector for C++, an ArrayList for Java, a defaultdict for Python, and an Array for JavaScript).(indices[arr[i]] contains all the indices where arr[i] appears)
2. For each element in arr, loop through the indices[arr[i]] and sum up the intervals between index i and other indices.
3. Add this sum to intervals[i] and return the intervals array.

## A solution in C++

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

vector<int> sumOfIntervals(vector<int>& arr) {
    int n = arr.size();
    vector<vector<int>> indices(101);
    vector<int> intervals(n, 0);

    for (int i = 0; i < n; ++i) {
        indices[arr[i]].push_back(i);
    }

    for (int i = 0; i < n; ++i) {
        for (int index : indices[arr[i]]) {
            intervals[i] += abs(index - i);
        }
    }

    return intervals;
}
```
1. Store the indices of each element in arr in a separate data structure (in this case, a vector for C++, an ArrayList for Java, a defaultdict for Python, and an Array for JavaScript).(indices[arr[i]] contains all the indices where arr[i] appears)
2. For each element in arr, loop through the indices[arr[i]] and sum up the intervals between index i and other indices.
3. Add this sum to intervals[i] and return the intervals array.

## A solution in Python

```python
from collections import defaultdict

def sum_of_intervals(arr):
    n = len(arr)
    indices = defaultdict(list)
    intervals = [0] * n

    for i in range(n):
        indices[arr[i]].append(i)

    for i in range(n):
        for index in indices[arr[i]]:
            intervals[i] += abs(index - i)

    return intervals
```
1. Store the indices of each element in arr in a separate data structure (in this case, a vector for C++, an ArrayList for Java, a defaultdict for Python, and an Array for JavaScript).(indices[arr[i]] contains all the indices where arr[i] appears)
2. For each element in arr, loop through the indices[arr[i]] and sum up the intervals between index i and other indices.
3. Add this sum to intervals[i] and return the intervals array.

## A solution in Javascript

```javascript
function sumOfIntervals(arr) {
    const n = arr.length;
    const indices = Array.from({ length: 101 }, () => []);
    const intervals = Array(n).fill(0);

    for (let i = 0; i < n; ++i) {
        indices[arr[i]].push(i);
    }

    for (let i = 0; i < n; ++i) {
        for (const index of indices[arr[i]]) {
            intervals[i] += Math.abs(index - i);
        }
    }

    return intervals;
}
```
1. Store the indices of each element in arr in a separate data structure (in this case, a vector for C++, an ArrayList for Java, a defaultdict for Python, and an Array for JavaScript).(indices[arr[i]] contains all the indices where arr[i] appears)
2. For each element in arr, loop through the indices[arr[i]] and sum up the intervals between index i and other indices.
3. Add this sum to intervals[i] and return the intervals array.


# Design an ATM Machine

- slug: design-an-atm-machine
- difficulty: Medium

There is an ATM machine that stores banknotes of `5` denominations: `20`, `50`, `100`, `200`, and `500` dollars. Initially the ATM is empty. The user can use the machine to deposit or withdraw any amount of money.

When withdrawing, the machine prioritizes using banknotes of **larger** values.

*   For example, if you want to withdraw `$300` and there are `2` `$50` banknotes, `1` `$100` banknote, and `1` `$200` banknote, then the machine will use the `$100` and `$200` banknotes.
*   However, if you try to withdraw `$600` and there are `3` `$200` banknotes and `1` `$500` banknote, then the withdraw request will be rejected because the machine will first try to use the `$500` banknote and then be unable to use banknotes to complete the remaining `$100`. Note that the machine is **not** allowed to use the `$200` banknotes instead of the `$500` banknote.

Implement the ATM class:

*   `ATM()` Initializes the ATM object.
*   `void deposit(int[] banknotesCount)` Deposits new banknotes in the order `$20`, `$50`, `$100`, `$200`, and `$500`.
*   `int[] withdraw(int amount)` Returns an array of length `5` of the number of banknotes that will be handed to the user in the order `$20`, `$50`, `$100`, `$200`, and `$500`, and update the number of banknotes in the ATM after withdrawing. Returns `[-1]` if it is not possible (do **not** withdraw any banknotes in this case).

**Example 1:**

**Input**
\[ "ATM ",  "deposit ",  "withdraw ",  "deposit ",  "withdraw ",  "withdraw "\]
\[\[\], \[\[0,0,1,2,1\]\], \[600\], \[\[0,1,0,1,1\]\], \[600\], \[550\]\]
**Output**
\[null, null, \[0,0,1,0,1\], null, \[-1\], \[0,1,0,0,1\]\]

**Explanation**
ATM atm = new ATM();
atm.deposit(\[0,0,1,2,1\]); // Deposits 1 $100 banknote, 2 $200 banknotes,
                          // and 1 $500 banknote.
atm.withdraw(600);        // Returns \[0,0,1,0,1\]. The machine uses 1 $100 banknote
                          // and 1 $500 banknote. The banknotes left over in the
                          // machine are \[0,0,0,2,0\].
atm.deposit(\[0,1,0,1,1\]); // Deposits 1 $50, $200, and $500 banknote.
                          // The banknotes in the machine are now \[0,1,0,3,1\].
atm.withdraw(600);        // Returns \[-1\]. The machine will try to use a $500 banknote
                          // and then be unable to complete the remaining $100,
                          // so the withdraw request will be rejected.
                          // Since the request is rejected, the number of banknotes
                          // in the machine is not modified.
atm.withdraw(550);        // Returns \[0,1,0,0,1\]. The machine uses 1 $50 banknote
                          // and 1 $500 banknote.

**Constraints:**

*   `banknotesCount.length == 5`
*   `0 <= banknotesCount[i] <= 109`
*   `1 <= amount <= 109`
*   At most `5000` calls **in total** will be made to `withdraw` and `deposit`.
*   At least **one** call will be made to each function `withdraw` and `deposit`.

## A solution in Java

```java
import java.util.Arrays;

public int[] recoverArray(int n, int[] nums) {
    Arrays.sort(nums);
    int[] arr = new int[n];
    for (int i = 0; i < n; i++) {
        arr[i] = nums[i * 2];
    }
    return arr;
}
```
The algorithm to solve the problem is the same for all the languages. The steps are:

1. Sort the given `nums` array in non-descending order.
2. Iterate from 0 to `n-1` (inclusive), and for each index `i`, add the number at index `(2*i)` of the sorted `nums` array to the resulting `arr`.
3. Return the resulting `arr`.

This works because the sorted `nums` array will have lower integers mixed with higher integers. Given that we have exactly n lower integers and n higher integers, picking every other number (starting at index 0) will give us the desired original array.

## A solution in C++

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

vector<int> recoverArray(int n, vector<int>& nums) {
    sort(nums.begin(), nums.end());
    vector<int> arr(n);
    for (int i = 0; i < n; ++i) {
        arr[i] = nums[i * 2];
    }
    return arr;
}
```
The algorithm to solve the problem is the same for all the languages. The steps are:

1. Sort the given `nums` array in non-descending order.
2. Iterate from 0 to `n-1` (inclusive), and for each index `i`, add the number at index `(2*i)` of the sorted `nums` array to the resulting `arr`.
3. Return the resulting `arr`.

This works because the sorted `nums` array will have lower integers mixed with higher integers. Given that we have exactly n lower integers and n higher integers, picking every other number (starting at index 0) will give us the desired original array.

## A solution in Python

```python
def recoverArray(n, nums):
    nums.sort()
    arr = [nums[i * 2] for i in range(n)]
    return arr
```
The algorithm to solve the problem is the same for all the languages. The steps are:

1. Sort the given `nums` array in non-descending order.
2. Iterate from 0 to `n-1` (inclusive), and for each index `i`, add the number at index `(2*i)` of the sorted `nums` array to the resulting `arr`.
3. Return the resulting `arr`.

This works because the sorted `nums` array will have lower integers mixed with higher integers. Given that we have exactly n lower integers and n higher integers, picking every other number (starting at index 0) will give us the desired original array.

## A solution in Javascript

```javascript
function recoverArray(n, nums) {
    nums.sort((a, b) => a - b);
    const arr = new Array(n);
    for (let i = 0; i < n; i++) {
        arr[i] = nums[i * 2];
    }
    return arr;
}
```
The algorithm to solve the problem is the same for all the languages. The steps are:

1. Sort the given `nums` array in non-descending order.
2. Iterate from 0 to `n-1` (inclusive), and for each index `i`, add the number at index `(2*i)` of the sorted `nums` array to the resulting `arr`.
3. Return the resulting `arr`.

This works because the sorted `nums` array will have lower integers mixed with higher integers. Given that we have exactly n lower integers and n higher integers, picking every other number (starting at index 0) will give us the desired original array.


# Maximum Score of a Node Sequence

- slug: maximum-score-of-a-node-sequence
- difficulty: Hard

There is an **undirected** graph with `n` nodes, numbered from `0` to `n - 1`.

You are given a **0-indexed** integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an **undirected** edge connecting nodes `ai` and `bi`.

A node sequence is **valid** if it meets the following conditions:

*   There is an edge connecting every pair of **adjacent** nodes in the sequence.
*   No node appears more than once in the sequence.

The score of a node sequence is defined as the **sum** of the scores of the nodes in the sequence.

Return _the **maximum score** of a valid node sequence with a length of_ `4`_._ If no such sequence exists, return `-1`.

**Example 1:**

**Input:** scores = \[5,2,9,8,4\], edges = \[\[0,1\],\[1,2\],\[2,3\],\[0,2\],\[1,3\],\[2,4\]\]
**Output:** 24
**Explanation:** The figure above shows the graph and the chosen node sequence \[0,1,2,3\].
The score of the node sequence is 5 + 2 + 9 + 8 = 24.
It can be shown that no other node sequence has a score of more than 24.
Note that the sequences \[3,1,2,0\] and \[1,0,2,3\] are also valid and have a score of 24.
The sequence \[0,3,2,4\] is not valid since no edge connects nodes 0 and 3.

**Example 2:**

**Input:** scores = \[9,20,6,4,11,12\], edges = \[\[0,3\],\[5,3\],\[2,4\],\[1,3\]\]
**Output:** -1
**Explanation:** The figure above shows the graph.
There are no valid node sequences of length 4, so we return -1.

**Constraints:**

*   `n == scores.length`
*   `4 <= n <= 5 * 104`
*   `1 <= scores[i] <= 108`
*   `0 <= edges.length <= 5 * 104`
*   `edges[i].length == 2`
*   `0 <= ai, bi <= n - 1`
*   `ai != bi`
*   There are no duplicate edges.

## A solution in Java

```java
public int maxScore(int[] scores, int[][] edges) {
    ArrayList<ArrayList<Integer>> adj_list = new ArrayList<>(scores.length);
    for (int i = 0; i < scores.length; i++) {
        adj_list.add(new ArrayList<>());
    }

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

    int result = -1;
    for (int[] edge : edges) {
        for (int neighbor : adj_list.get(edge[0])) {
            for (int next : adj_list.get(edge[1])) {
                if (next != neighbor && next != edge[0]) {
                    result = Math.max(result, scores[edge[0]] + scores[edge[1]] + scores[neighbor] + scores[next]);
                }
            }
        }
    }

    return result;
}
```
The algorithm first constructs an adjacency list from the given edges. An adjacency list is a data structure where each node is associated with a list of its neighboring nodes. Then, for each edge in the given graph, it checks all possible combinations of reachable nodes and calculates the sum of their scores, updating the result with the maximum score found. If no valid combination is found, the function returns -1 as specified.

## A solution in C++

```cpp
int maxScore(vector<int>& scores, vector<vector<int>>& edges) {
    vector<vector<int>> adj_list(scores.size());
    int result = -1;

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

    for (const auto& edge : edges) {
        for (int neighbor : adj_list[edge[0]]) {
            for (int next : adj_list[edge[1]]) {
                if (next != neighbor && next != edge[0]) {
                    result = max(result, scores[edge[0]] + scores[edge[1]] + scores[neighbor] + scores[next]);
                }
            }
        }
    }

    return result;
}
```
The algorithm first constructs an adjacency list from the given edges. An adjacency list is a data structure where each node is associated with a list of its neighboring nodes. Then, for each edge in the given graph, it checks all possible combinations of reachable nodes and calculates the sum of their scores, updating the result with the maximum score found. If no valid combination is found, the function returns -1 as specified.

## A solution in Python

```python
def maxScore(scores, edges):
    adj_list = [[] for _ in range(len(scores))]
    result = -1

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

    for edge in edges:
        for neighbor in adj_list[edge[0]]:
            for next in adj_list[edge[1]]:
                if next != neighbor and next != edge[0]:
                    result = max(result, scores[edge[0]] + scores[edge[1]] + scores[neighbor] + scores[next])

    return result
```
The algorithm first constructs an adjacency list from the given edges. An adjacency list is a data structure where each node is associated with a list of its neighboring nodes. Then, for each edge in the given graph, it checks all possible combinations of reachable nodes and calculates the sum of their scores, updating the result with the maximum score found. If no valid combination is found, the function returns -1 as specified.

## A solution in Javascript

```javascript
function maxScore(scores, edges) {
    const adj_list = new Array(scores.length).fill(null).map(() => []);
    let result = -1;

    for (const edge of edges) {
        adj_list[edge[0]].push(edge[1]);
        adj_list[edge[1]].push(edge[0]);
    }

    for (const edge of edges) {
        for (const neighbor of adj_list[edge[0]]) {
            for (const next of adj_list[edge[1]]) {
                if (next !== neighbor && next !== edge[0]) {
                    result = Math.max(result, scores[edge[0]] + scores[edge[1]] + scores[neighbor] + scores[next]);
                }
            }
        }
    }

    return result;
}
```
The algorithm first constructs an adjacency list from the given edges. An adjacency list is a data structure where each node is associated with a list of its neighboring nodes. Then, for each edge in the given graph, it checks all possible combinations of reachable nodes and calculates the sum of their scores, updating the result with the maximum score found. If no valid combination is found, the function returns -1 as specified.


# Calculate Digit Sum of a String

- slug: calculate-digit-sum-of-a-string
- difficulty: Easy

You are given a string `s` consisting of digits and an integer `k`.

A **round** can be completed if the length of `s` is greater than `k`. In one round, do the following:

1.  **Divide** `s` into **consecutive groups** of size `k` such that the first `k` characters are in the first group, the next `k` characters are in the second group, and so on. **Note** that the size of the last group can be smaller than `k`.
2.  **Replace** each group of `s` with a string representing the sum of all its digits. For example, `"346 "` is replaced with `"13 "` because `3 + 4 + 6 = 13`.
3.  **Merge** consecutive groups together to form a new string. If the length of the string is greater than `k`, repeat from step `1`.

Return `s` _after all rounds have been completed_.

**Example 1:**

**Input:** s =  "11111222223 ", k = 3
**Output:**  "135 "
**Explanation:**
- For the first round, we divide s into groups of size 3:  "111 ",  "112 ",  "222 ", and  "23 ".
  Then we calculate the digit sum of each group: 1 + 1 + 1 = 3, 1 + 1 + 2 = 4, 2 + 2 + 2 = 6, and 2 + 3 = 5.
  So, s becomes  "3 " +  "4 " +  "6 " +  "5 " =  "3465 " after the first round.
- For the second round, we divide s into  "346 " and  "5 ".
  Then we calculate the digit sum of each group: 3 + 4 + 6 = 13, 5 = 5.
  So, s becomes  "13 " +  "5 " =  "135 " after second round.
Now, s.length <= k, so we return  "135 " as the answer.

**Example 2:**

**Input:** s =  "00000000 ", k = 3
**Output:**  "000 "
**Explanation:**
We divide s into  "000 ",  "000 ", and  "00 ".
Then we calculate the digit sum of each group: 0 + 0 + 0 = 0, 0 + 0 + 0 = 0, and 0 + 0 = 0.
s becomes  "0 " +  "0 " +  "0 " =  "000 ", whose length is equal to k, so we return  "000 ".

**Constraints:**

*   `1 <= s.length <= 100`
*   `2 <= k <= 100`
*   `s` consists of digits only.

## A solution in Java

```java
boolean isAOnlyBeforeB(String s) {
    int lastIndexA = -1;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == 'a') {
            lastIndexA = i;
        } else if (s.charAt(i) == 'b' && lastIndexA > -1) {
            return false;
        }
    }
    return true;
}
```
The algorithm iterates through each character in the given string `s`. It maintains a variable called `lastIndexA` that keeps track of the last index where the character 'a' is found. If it encounters 'a', it updates `lastIndexA` with the current index. If it encounters 'b' and `lastIndexA` is not set to `-1` (meaning there was an 'a' before it), the algorithm returns `false`. If the loop completes without returning `false`, it means that every 'a' appears before every 'b', so the algorithm returns `true`.

## A solution in C++

```cpp
bool isAOnlyBeforeB(const std::string& s) {
    int lastIndexA = -1;
    for (size_t i = 0; i < s.length(); ++i) {
        if (s[i] == 'a') {
            lastIndexA = i;
        } else if (s[i] == 'b' && lastIndexA > -1) {
            return false;
        }
    }
    return true;
}
```
The algorithm iterates through each character in the given string `s`. It maintains a variable called `lastIndexA` that keeps track of the last index where the character 'a' is found. If it encounters 'a', it updates `lastIndexA` with the current index. If it encounters 'b' and `lastIndexA` is not set to `-1` (meaning there was an 'a' before it), the algorithm returns `false`. If the loop completes without returning `false`, it means that every 'a' appears before every 'b', so the algorithm returns `true`.

## A solution in Python

```python
def is_a_only_before_b(s: str) -> bool:
    last_index_a = -1
    for i, c in enumerate(s):
        if c == 'a':
            last_index_a = i
        elif c == 'b' and last_index_a > -1:
            return False
    return True
```
The algorithm iterates through each character in the given string `s`. It maintains a variable called `lastIndexA` that keeps track of the last index where the character 'a' is found. If it encounters 'a', it updates `lastIndexA` with the current index. If it encounters 'b' and `lastIndexA` is not set to `-1` (meaning there was an 'a' before it), the algorithm returns `false`. If the loop completes without returning `false`, it means that every 'a' appears before every 'b', so the algorithm returns `true`.

## A solution in Javascript

```javascript
function isAOnlyBeforeB(s) {
    let lastIndexA = -1;
    for (let i = 0; i < s.length; i++) {
        if (s.charAt(i) === 'a') {
            lastIndexA = i;
        } else if (s.charAt(i) === 'b' && lastIndexA > -1) {
            return false;
        }
    }
    return true;
}
```
The algorithm iterates through each character in the given string `s`. It maintains a variable called `lastIndexA` that keeps track of the last index where the character 'a' is found. If it encounters 'a', it updates `lastIndexA` with the current index. If it encounters 'b' and `lastIndexA` is not set to `-1` (meaning there was an 'a' before it), the algorithm returns `false`. If the loop completes without returning `false`, it means that every 'a' appears before every 'b', so the algorithm returns `true`.


# Minimum Rounds to Complete All Tasks

- slug: minimum-rounds-to-complete-all-tasks
- difficulty: Medium

You are given a **0-indexed** integer array `tasks`, where `tasks[i]` represents the difficulty level of a task. In each round, you can complete either 2 or 3 tasks of the **same difficulty level**.

Return _the **minimum** rounds required to complete all the tasks, or_ `-1` _if it is not possible to complete all the tasks._

**Example 1:**

**Input:** tasks = \[2,2,3,3,2,4,4,4,4,4\]
**Output:** 4
**Explanation:** To complete all the tasks, a possible plan is:
- In the first round, you complete 3 tasks of difficulty level 2.
- In the second round, you complete 2 tasks of difficulty level 3.
- In the third round, you complete 3 tasks of difficulty level 4.
- In the fourth round, you complete 2 tasks of difficulty level 4.
It can be shown that all the tasks cannot be completed in fewer than 4 rounds, so the answer is 4.

**Example 2:**

**Input:** tasks = \[2,3,3\]
**Output:** -1
**Explanation:** There is only 1 task of difficulty level 2, but in each round, you can only complete either 2 or 3 tasks of the same difficulty level. Hence, you cannot complete all the tasks, and the answer is -1.

**Constraints:**

*   `1 <= tasks.length <= 105`
*   `1 <= tasks[i] <= 109`

## A solution in Java

```java
public int numOfBeams(String[] bank) {
    int m = bank.length;
    int n = bank[0].length();
    int beams = 0;

    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            if (bank[i].charAt(j) == '1') {
                for (int k = j + 1; k < n && bank[i].charAt(k) != '1'; k++) {
                    beams += bank[i].charAt(k) == '0' ? 1 : 0;
                }
                for (int k = i + 1; k < m && bank[k].charAt(j) != '1'; k++) {
                    beams += bank[k].charAt(j) == '0' ? 1 : 0;
                }
            }
        }
    }

    return beams;
}
```
We are given a bank floor plan where '0' represents an empty cell and '1' represents a cell with a security device. We have to find the number of laser beams between any two security devices. The laser beams are independent and do not interfere or join with one another.

The algorithm iterates through each cell in the 2D matrix. If the cell has a security device (i.e., its value is '1'), we check the cells to the right and below the current cell until we find another security device. For each empty cell (i.e., cells with '0') between security devices, we increment the beam count. Once we reach another security device, we move on to the next cell in the floor plan.

After iterating through all cells, we return the total number of laser beams in the bank's floor plan.

## A solution in C++

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

int numOfBeams(vector<string>& bank) {
    int m = bank.size();
    int n = bank[0].size();
    int beams = 0;

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (bank[i][j] == '1') {
                for (int k = j + 1; k < n && bank[i][k] != '1'; ++k) {
                    beams += bank[i][k] == '0';
                }
                for (int k = i + 1; k < m && bank[k][j] != '1'; ++k) {
                    beams += bank[k][j] == '0';
                }
            }
        }
    }

    return beams;
}
```
We are given a bank floor plan where '0' represents an empty cell and '1' represents a cell with a security device. We have to find the number of laser beams between any two security devices. The laser beams are independent and do not interfere or join with one another.

The algorithm iterates through each cell in the 2D matrix. If the cell has a security device (i.e., its value is '1'), we check the cells to the right and below the current cell until we find another security device. For each empty cell (i.e., cells with '0') between security devices, we increment the beam count. Once we reach another security device, we move on to the next cell in the floor plan.

After iterating through all cells, we return the total number of laser beams in the bank's floor plan.

## A solution in Python

```python
def numOfBeams(bank):
    m = len(bank)
    n = len(bank[0])
    beams = 0

    for i in range(m):
        for j in range(n):
            if bank[i][j] == '1':
                k = j + 1
                while k < n and bank[i][k] != '1':
                    beams += bank[i][k] == '0'
                    k += 1
                k = i + 1
                while k < m and bank[k][j] != '1':
                    beams += bank[k][j] == '0'
                    k += 1

    return beams
```
We are given a bank floor plan where '0' represents an empty cell and '1' represents a cell with a security device. We have to find the number of laser beams between any two security devices. The laser beams are independent and do not interfere or join with one another.

The algorithm iterates through each cell in the 2D matrix. If the cell has a security device (i.e., its value is '1'), we check the cells to the right and below the current cell until we find another security device. For each empty cell (i.e., cells with '0') between security devices, we increment the beam count. Once we reach another security device, we move on to the next cell in the floor plan.

After iterating through all cells, we return the total number of laser beams in the bank's floor plan.

## A solution in Javascript

```javascript
function numOfBeams(bank) {
    let m = bank.length;
    let n = bank[0].length;
    let beams = 0;

    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            if (bank[i][j] == '1') {
                let k = j + 1;
                while (k < n && bank[i][k] != '1') {
                    beams += bank[i][k] == '0' ? 1 : 0;
                    k++;
                }
                k = i + 1;
                while (k < m && bank[k][j] != '1') {
                    beams += bank[k][j] == '0' ? 1 : 0;
                    k++;
                }
            }
        }
    }

    return beams;
}
```
We are given a bank floor plan where '0' represents an empty cell and '1' represents a cell with a security device. We have to find the number of laser beams between any two security devices. The laser beams are independent and do not interfere or join with one another.

The algorithm iterates through each cell in the 2D matrix. If the cell has a security device (i.e., its value is '1'), we check the cells to the right and below the current cell until we find another security device. For each empty cell (i.e., cells with '0') between security devices, we increment the beam count. Once we reach another security device, we move on to the next cell in the floor plan.

After iterating through all cells, we return the total number of laser beams in the bank's floor plan.


# Maximum Trailing Zeros in a Cornered Path

- slug: maximum-trailing-zeros-in-a-cornered-path
- difficulty: Medium

You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer.

A **cornered path** is defined as a set of adjacent cells with **at most** one turn. More specifically, the path should exclusively move either **horizontally** or **vertically** up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the **alternate** direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.

The **product** of a path is defined as the product of all the values in the path.

Return _the **maximum** number of **trailing zeros** in the product of a cornered path found in_ `grid`.

Note:

*   **Horizontal** movement means moving in either the left or right direction.
*   **Vertical** movement means moving in either the up or down direction.

**Example 1:**

**Input:** grid = \[\[23,17,15,3,20\],\[8,1,20,27,11\],\[9,4,6,2,21\],\[40,9,1,10,6\],\[22,7,4,5,3\]\]
**Output:** 3
**Explanation:** The grid on the left shows a valid cornered path.
It has a product of 15 \* 20 \* 6 \* 1 \* 10 = 18000 which has 3 trailing zeros.
It can be shown that this is the maximum trailing zeros in the product of a cornered path.

The grid in the middle is not a cornered path as it has more than one turn.
The grid on the right is not a cornered path as it requires a return to a previously visited cell.

**Example 2:**

**Input:** grid = \[\[4,3,2\],\[7,6,1\],\[8,8,8\]\]
**Output:** 0
**Explanation:** The grid is shown in the figure above.
There are no cornered paths in the grid that result in a product with a trailing zero.

**Constraints:**

*   `m == grid.length`
*   `n == grid[i].length`
*   `1 <= m, n <= 105`
*   `1 <= m * n <= 105`
*   `1 <= grid[i][j] <= 1000`

## A solution in Java

```java
public boolean canDestroyAllAsteroids(int mass, int[] asteroids) {
    Arrays.sort(asteroids);
    for (int asteroid : asteroids) {
        if (mass >= asteroid) {
            mass += asteroid;
        } else {
            return false;
        }
    }
    return true;
}
```
1. Sort the `asteroids` array in ascending order. This ensures that we arrange the collision of the planet with the smaller asteroid masses first, which maximizes the chances of destroying all asteroids.
2. Iterate through the sorted `asteroids` array.
3. For each asteroid mass, check if the planet's mass is greater than or equal to the asteroid's mass.
   - If it is, add the asteroid mass to the planet's mass (the planet gains the mass of the asteroid after a successful collision).
   - If not, then the planet is destroyed and we return `false` as not all asteroids can be destroyed.
4. If the loop completes without returning `false`, this means we successfully destroyed all asteroids and we return `true`.

## A solution in C++

```cpp
bool canDestroyAllAsteroids(int mass, vector<int>& asteroids) {
    sort(asteroids.begin(), asteroids.end());
    for (int asteroid : asteroids) {
        if (mass >= asteroid) {
            mass += asteroid;
        } else {
            return false;
        }
    }
    return true;
}
```
1. Sort the `asteroids` array in ascending order. This ensures that we arrange the collision of the planet with the smaller asteroid masses first, which maximizes the chances of destroying all asteroids.
2. Iterate through the sorted `asteroids` array.
3. For each asteroid mass, check if the planet's mass is greater than or equal to the asteroid's mass.
   - If it is, add the asteroid mass to the planet's mass (the planet gains the mass of the asteroid after a successful collision).
   - If not, then the planet is destroyed and we return `false` as not all asteroids can be destroyed.
4. If the loop completes without returning `false`, this means we successfully destroyed all asteroids and we return `true`.

## A solution in Python

```python
def can_destroy_all_asteroids(mass, asteroids):
    asteroids.sort()
    for asteroid in asteroids:
        if mass >= asteroid:
            mass += asteroid
        else:
            return False
    return True
```
1. Sort the `asteroids` array in ascending order. This ensures that we arrange the collision of the planet with the smaller asteroid masses first, which maximizes the chances of destroying all asteroids.
2. Iterate through the sorted `asteroids` array.
3. For each asteroid mass, check if the planet's mass is greater than or equal to the asteroid's mass.
   - If it is, add the asteroid mass to the planet's mass (the planet gains the mass of the asteroid after a successful collision).
   - If not, then the planet is destroyed and we return `false` as not all asteroids can be destroyed.
4. If the loop completes without returning `false`, this means we successfully destroyed all asteroids and we return `true`.

## A solution in Javascript

```javascript
function canDestroyAllAsteroids(mass, asteroids) {
    asteroids.sort((a, b) => a - b);
    for (const asteroid of asteroids) {
        if (mass >= asteroid) {
            mass += asteroid;
        } else {
            return false;
        }
    }
    return true;
}
```
1. Sort the `asteroids` array in ascending order. This ensures that we arrange the collision of the planet with the smaller asteroid masses first, which maximizes the chances of destroying all asteroids.
2. Iterate through the sorted `asteroids` array.
3. For each asteroid mass, check if the planet's mass is greater than or equal to the asteroid's mass.
   - If it is, add the asteroid mass to the planet's mass (the planet gains the mass of the asteroid after a successful collision).
   - If not, then the planet is destroyed and we return `false` as not all asteroids can be destroyed.
4. If the loop completes without returning `false`, this means we successfully destroyed all asteroids and we return `true`.


# Longest Path With Different Adjacent Characters

- slug: longest-path-with-different-adjacent-characters
- difficulty: Hard

You are given a **tree** (i.e. a connected, undirected graph that has no cycles) **rooted** at node `0` consisting of `n` nodes numbered from `0` to `n - 1`. The tree is represented by a **0-indexed** array `parent` of size `n`, where `parent[i]` is the parent of node `i`. Since node `0` is the root, `parent[0] == -1`.

You are also given a string `s` of length `n`, where `s[i]` is the character assigned to node `i`.

Return _the length of the **longest path** in the tree such that no pair of **adjacent** nodes on the path have the same character assigned to them._

**Example 1:**

**Input:** parent = \[-1,0,0,1,1,2\], s =  "abacbe "
**Output:** 3
**Explanation:** The longest path where each two adjacent nodes have different characters in the tree is the path: 0 -> 1 -> 3. The length of this path is 3, so 3 is returned.
It can be proven that there is no longer path that satisfies the conditions.

**Example 2:**

**Input:** parent = \[-1,0,0,0\], s =  "aabc "
**Output:** 3
**Explanation:** The longest path where each two adjacent nodes have different characters is the path: 2 -> 0 -> 3. The length of this path is 3, so 3 is returned.

**Constraints:**

*   `n == parent.length == s.length`
*   `1 <= n <= 105`
*   `0 <= parent[i] <= n - 1` for all `i >= 1`
*   `parent[0] == -1`
*   `parent` represents a valid tree.
*   `s` consists of only lowercase English letters.

## A solution in Java

```java
import java.util.*;

public int maxInvites(int[] favorite) {
    int n = favorite.length;
    int[] dp = new int[n];
    int maxInvites = 0;

    for (int i = 0; i < n; i++) {
        dp[i] = (i == favorite[favorite[i]]) ? 2 : 1;
        maxInvites = Math.max(maxInvites, dp[i]);
    }

    return maxInvites;
}
```
The algorithm consists of iterating through the list of favorite employees and checking if the favorite person of the current employee also has the current employee as their favorite. In that case, both can be invited to the meeting, as they can sit next to each other. For simplicity, use an array `dp` to store the number of invitees for each employee. If they can be invited together with their favorite person, set `dp[i] = 2`. Otherwise, set `dp[i] = 1`, as they can't be invited with their favorite person.

Finally, iterate through the `dp` array and find the maximum number of employees that can be invited to the meeting. Return this value.

## A solution in C++

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

int maxInvites(std::vector<int>& favorite) {
    int n = favorite.size();
    std::vector<int> dp(n, 0);
    int max_invites = 0;

    for (int i = 0; i < n; ++i) {
        dp[i] = (i == favorite[favorite[i]]) ? 2 : 1;
        max_invites = std::max(max_invites, dp[i]);
    }

    return max_invites;
}
```
The algorithm consists of iterating through the list of favorite employees and checking if the favorite person of the current employee also has the current employee as their favorite. In that case, both can be invited to the meeting, as they can sit next to each other. For simplicity, use an array `dp` to store the number of invitees for each employee. If they can be invited together with their favorite person, set `dp[i] = 2`. Otherwise, set `dp[i] = 1`, as they can't be invited with their favorite person.

Finally, iterate through the `dp` array and find the maximum number of employees that can be invited to the meeting. Return this value.

## A solution in Python

```python
def max_invites(favorite):
    n = len(favorite)
    dp = [0] * n
    max_invites = 0

    for i in range(n):
        dp[i] = 2 if i == favorite[favorite[i]] else 1
        max_invites = max(max_invites, dp[i])

    return max_invites
```
The algorithm consists of iterating through the list of favorite employees and checking if the favorite person of the current employee also has the current employee as their favorite. In that case, both can be invited to the meeting, as they can sit next to each other. For simplicity, use an array `dp` to store the number of invitees for each employee. If they can be invited together with their favorite person, set `dp[i] = 2`. Otherwise, set `dp[i] = 1`, as they can't be invited with their favorite person.

Finally, iterate through the `dp` array and find the maximum number of employees that can be invited to the meeting. Return this value.

## A solution in Javascript

```javascript
function maxInvites(favorite) {
    const n = favorite.length;
    const dp = new Array(n).fill(0);
    let maxInvites = 0;

    for (let i = 0; i < n; i++) {
        dp[i] = (i === favorite[favorite[i]]) ? 2 : 1;
        maxInvites = Math.max(maxInvites, dp[i]);
    }

    return maxInvites;
}
```
The algorithm consists of iterating through the list of favorite employees and checking if the favorite person of the current employee also has the current employee as their favorite. In that case, both can be invited to the meeting, as they can sit next to each other. For simplicity, use an array `dp` to store the number of invitees for each employee. If they can be invited together with their favorite person, set `dp[i] = 2`. Otherwise, set `dp[i] = 1`, as they can't be invited with their favorite person.

Finally, iterate through the `dp` array and find the maximum number of employees that can be invited to the meeting. Return this value.


# Maximum Cost of Trip With K Highways

- slug: maximum-cost-of-trip-with-k-highways
- difficulty: Hard

A series of highways connect `n` cities numbered from `0` to `n - 1`. You are given a 2D integer array `highways` where `highways[i] = [city1i, city2i, tolli]` indicates that there is a highway that connects `city1i` and `city2i`, allowing a car to go from `city1i` to `city2i` and **vice versa** for a cost of `tolli`.

You are also given an integer `k`. You are going on a trip that crosses **exactly** `k` highways. You may start at any city, but you may only visit each city **at most** once during your trip.

Return _the **maximum** cost of your trip. If there is no trip that meets the requirements, return_ `-1`_._

**Example 1:**

**Input:** n = 5, highways = \[\[0,1,4\],\[2,1,3\],\[1,4,11\],\[3,2,3\],\[3,4,2\]\], k = 3
**Output:** 17
**Explanation:**
One possible trip is to go from 0 -> 1 -> 4 -> 3. The cost of this trip is 4 + 11 + 2 = 17.
Another possible trip is to go from 4 -> 1 -> 2 -> 3. The cost of this trip is 11 + 3 + 3 = 17.
It can be proven that 17 is the maximum possible cost of any valid trip.

Note that the trip 4 -> 1 -> 0 -> 1 is not allowed because you visit the city 1 twice.

**Example 2:**

**Input:** n = 4, highways = \[\[0,1,3\],\[2,3,2\]\], k = 2
**Output:** -1
**Explanation:** There are no valid trips of length 2, so return -1.

**Constraints:**

*   `2 <= n <= 15`
*   `1 <= highways.length <= 50`
*   `highways[i].length == 3`
*   `0 <= city1i, city2i <= n - 1`
*   `city1i != city2i`
*   `0 <= tolli <= 100`
*   `1 <= k <= 50`
*   There are no duplicate highways.

## A solution in Java

```java
import java.util.List;

public int dfs(int currCity, int remainingHighways, int costSoFar, List<List<Integer>> highways, boolean[] visited) {
    if (remainingHighways == 0) {
        return costSoFar;
    }

    visited[currCity] = true;
    int maxCost = -1;

    for (List<Integer> highway : highways) {
        int nextCity = -1;
        if (highway.get(0) == currCity && !visited[highway.get(1)]) {
            nextCity = highway.get(1);
        } else if (highway.get(1) == currCity && !visited[highway.get(0)]) {
            nextCity = highway.get(0);
        }

        if (nextCity != -1) {
            int cost = dfs(nextCity, remainingHighways - 1, costSoFar + highway.get(2), highways, visited);
            maxCost = Math.max(maxCost, cost);
        }
    }

    visited[currCity] = false;
    return maxCost;
}

public int maxCost(int n, List<List<Integer>> highways, int k) {
    boolean[] visited = new boolean[n];
    int maxCost = -1;

    for (int i = 0; i < n; i++) {
        int cost = dfs(i, k, 0, highways, visited);
        maxCost = Math.max(maxCost, cost);
    }

    return maxCost;
}
```
The problem can be solved using a depth-first search (DFS) algorithm. First, create a helper function called `dfs` to traverse the graph formed by the cities and highways. This function takes the current city number, remaining number of highways, cost so far, highways data, and visited cities as its parameters.

In the DFS function, if the remaining number of highways is 0, return the cost accumulated so far. Iterate through each highway, find the next city, and ensure that it has not been visited already. If a valid next city is found, recursively call the DFS function with the updated cost and remaining highways. Keep track of the maximum cost obtained during each iteration, and return the maximum cost after completing the loop.

Finally, in the main function `maxCost`, initially set the maximum cost to -1. Iterate over each city, and for each city, perform a DFS traversal and find the cost for the trip starting at that city. Update the maximum cost if the calculated cost for the current city is higher than the present maximum cost. Return the maximum cost after iterating through all cities.

## A solution in C++

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

using namespace std;

int dfs(int curr_city, int remaining_highways, int cost_so_far, vector<vector<int>>& highways, vector<bool>& visited) {
    if (remaining_highways == 0) {
        return cost_so_far;
    }

    visited[curr_city] = true;
    int max_cost = -1;

    for (vector<int>& highway : highways) {
        int next_city = -1;
        if (highway[0] == curr_city && !visited[highway[1]]) {
            next_city = highway[1];
        } else if (highway[1] == curr_city && !visited[highway[0]]) {
            next_city = highway[0];
        }

        if (next_city != -1) {
            int cost = dfs(next_city, remaining_highways - 1, cost_so_far + highway[2], highways, visited);
            max_cost = max(max_cost, cost);
        }
    }

    visited[curr_city] = false;
    return max_cost;
}

int maxCost(int n, vector<vector<int>>& highways, int k) {
    vector<bool> visited(n, false);
    int max_cost = -1;

    for (int i = 0; i < n; i++) {
        int cost = dfs(i, k, 0, highways, visited);
        max_cost = max(max_cost, cost);
    }

    return max_cost;
}
```
The problem can be solved using a depth-first search (DFS) algorithm. First, create a helper function called `dfs` to traverse the graph formed by the cities and highways. This function takes the current city number, remaining number of highways, cost so far, highways data, and visited cities as its parameters.

In the DFS function, if the remaining number of highways is 0, return the cost accumulated so far. Iterate through each highway, find the next city, and ensure that it has not been visited already. If a valid next city is found, recursively call the DFS function with the updated cost and remaining highways. Keep track of the maximum cost obtained during each iteration, and return the maximum cost after completing the loop.

Finally, in the main function `maxCost`, initially set the maximum cost to -1. Iterate over each city, and for each city, perform a DFS traversal and find the cost for the trip starting at that city. Update the maximum cost if the calculated cost for the current city is higher than the present maximum cost. Return the maximum cost after iterating through all cities.

## A solution in Python

```python
def dfs(curr_city, remaining_highways, cost_so_far, highways, visited):
    if remaining_highways == 0:
        return cost_so_far

    visited[curr_city] = True
    max_cost = -1

    for highway in highways:
        next_city = -1
        if highway[0] == curr_city and not visited[highway[1]]:
            next_city = highway[1]
        elif highway[1] == curr_city and not visited[highway[0]]:
            next_city = highway[0]

        if next_city != -1:
            cost = dfs(next_city, remaining_highways - 1, cost_so_far + highway[2], highways, visited)
            max_cost = max(max_cost, cost)

    visited[curr_city] = False
    return max_cost

def max_cost(n, highways, k):
    visited = [False] * n
    max_cost = -1

    for i in range(n):
        cost = dfs(i, k, 0, highways, visited)
        max_cost = max(max_cost, cost)

    return max_cost
```
The problem can be solved using a depth-first search (DFS) algorithm. First, create a helper function called `dfs` to traverse the graph formed by the cities and highways. This function takes the current city number, remaining number of highways, cost so far, highways data, and visited cities as its parameters.

In the DFS function, if the remaining number of highways is 0, return the cost accumulated so far. Iterate through each highway, find the next city, and ensure that it has not been visited already. If a valid next city is found, recursively call the DFS function with the updated cost and remaining highways. Keep track of the maximum cost obtained during each iteration, and return the maximum cost after completing the loop.

Finally, in the main function `maxCost`, initially set the maximum cost to -1. Iterate over each city, and for each city, perform a DFS traversal and find the cost for the trip starting at that city. Update the maximum cost if the calculated cost for the current city is higher than the present maximum cost. Return the maximum cost after iterating through all cities.

## A solution in Javascript

```javascript
function dfs(currCity, remainingHighways, costSoFar, highways, visited) {
    if (remainingHighways === 0) {
        return costSoFar;
    }

    visited[currCity] = true;
    let maxCost = -1;

    for (let highway of highways) {
        let nextCity = -1;
        if (highway[0] === currCity && !visited[highway[1]]) {
            nextCity = highway[1];
        } else if (highway[1] === currCity && !visited[highway[0]]) {
            nextCity = highway[0];
        }

        if (nextCity !== -1) {
            const cost = dfs(nextCity, remainingHighways - 1, costSoFar + highway[2], highways, visited);
            maxCost = Math.max(maxCost, cost);
        }
    }

    visited[currCity] = false;
    return maxCost;
}

function maxCost(n, highways, k) {
    const visited = Array(n).fill(false);
    let maxCost = -1;

    for (let i = 0; i < n; i++) {
        const cost = dfs(i, k, 0, highways, visited);
        maxCost = Math.max(maxCost, cost);
    }

    return maxCost;
}
```
The problem can be solved using a depth-first search (DFS) algorithm. First, create a helper function called `dfs` to traverse the graph formed by the cities and highways. This function takes the current city number, remaining number of highways, cost so far, highways data, and visited cities as its parameters.

In the DFS function, if the remaining number of highways is 0, return the cost accumulated so far. Iterate through each highway, find the next city, and ensure that it has not been visited already. If a valid next city is found, recursively call the DFS function with the updated cost and remaining highways. Keep track of the maximum cost obtained during each iteration, and return the maximum cost after completing the loop.

Finally, in the main function `maxCost`, initially set the maximum cost to -1. Iterate over each city, and for each city, perform a DFS traversal and find the cost for the trip starting at that city. Update the maximum cost if the calculated cost for the current city is higher than the present maximum cost. Return the maximum cost after iterating through all cities.


# Intersection of Multiple Arrays

- slug: intersection-of-multiple-arrays
- difficulty: Easy

Given a 2D integer array `nums` where `nums[i]` is a non-empty array of **distinct** positive integers, return _the list of integers that are present in **each array** of_ `nums` _sorted in **ascending order**_.

**Example 1:**

**Input:** nums = \[\[**3**,1,2,**4**,5\],\[1,2,**3**,**4**\],\[**3**,**4**,5,6\]\]
**Output:** \[3,4\]
**Explanation:**
The only integers present in each of nums\[0\] = \[**3**,1,2,**4**,5\], nums\[1\] = \[1,2,**3**,**4**\], and nums\[2\] = \[**3**,**4**,5,6\] are 3 and 4, so we return \[3,4\].

**Example 2:**

**Input:** nums = \[\[1,2,3\],\[4,5,6\]\]
**Output:** \[\]
**Explanation:**
There does not exist any integer present both in nums\[0\] and nums\[1\], so we return an empty list \[\].

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `1 <= sum(nums[i].length) <= 1000`
*   `1 <= nums[i][j] <= 1000`
*   All the values of `nums[i]` are **unique**.

## A solution in Java

```java
import java.util.Arrays;

public int minCost(int[] cost) {
    Arrays.sort(cost);
    int n = cost.length;
    int min_cost = 0;

    for(int i = n - 1; i >= 0; i -= 3) {
        min_cost += cost[i];
        if(i - 1 >= 0) min_cost += cost[i - 1];
    }

    return min_cost;
}
```
The algorithm sorts all the candies in the array in descending order of cost, so that the most expensive candies are bought first. Then, it loops over the array, taking two candies at a time (the loop increments 3 positions each iteration) and adding their cost to the total `min_cost`. The choice of the third free candy will always be one of the two already chosen, so its cost is already included in `min_cost`. After iterating through the entire array, the function returns the minimum cost.

## A solution in C++

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

int minCost(std::vector<int>& cost) {
    std::sort(cost.begin(), cost.end(), std::greater<>());
    int n = cost.size();

    int min_cost = 0;

    for(int i = 0; i < n; i += 3) {
        min_cost += cost[i];
        if(i+1 < n) min_cost += cost[i+1];
    }

    return min_cost;
}
```
The algorithm sorts all the candies in the array in descending order of cost, so that the most expensive candies are bought first. Then, it loops over the array, taking two candies at a time (the loop increments 3 positions each iteration) and adding their cost to the total `min_cost`. The choice of the third free candy will always be one of the two already chosen, so its cost is already included in `min_cost`. After iterating through the entire array, the function returns the minimum cost.

## A solution in Python

```python
def min_cost(cost):
    cost.sort(reverse=True)
    n = len(cost)
    min_cost = 0

    for i in range(0, n, 3):
        min_cost += cost[i]
        if i+1 < n:
            min_cost += cost[i+1]

    return min_cost
```
The algorithm sorts all the candies in the array in descending order of cost, so that the most expensive candies are bought first. Then, it loops over the array, taking two candies at a time (the loop increments 3 positions each iteration) and adding their cost to the total `min_cost`. The choice of the third free candy will always be one of the two already chosen, so its cost is already included in `min_cost`. After iterating through the entire array, the function returns the minimum cost.

## A solution in Javascript

```javascript
function minCost(cost) {
    cost.sort((a, b) => b - a);
    const n = cost.length;
    let min_cost = 0;

    for(let i = 0; i < n; i += 3) {
        min_cost += cost[i];
        if(i+1 < n) min_cost += cost[i+1];
    }

    return min_cost;
}
```
The algorithm sorts all the candies in the array in descending order of cost, so that the most expensive candies are bought first. Then, it loops over the array, taking two candies at a time (the loop increments 3 positions each iteration) and adding their cost to the total `min_cost`. The choice of the third free candy will always be one of the two already chosen, so its cost is already included in `min_cost`. After iterating through the entire array, the function returns the minimum cost.