# Find Good Days to Rob the Bank

- slug: find-good-days-to-rob-the-bank
- difficulty: Medium

You and a gang of thieves are planning on robbing a bank. You are given a **0-indexed** integer array `security`, where `security[i]` is the number of guards on duty on the `ith` day. The days are numbered starting from `0`. You are also given an integer `time`.

The `ith` day is a good day to rob the bank if:

*   There are at least `time` days before and after the `ith` day,
*   The number of guards at the bank for the `time` days **before** `i` are **non-increasing**, and
*   The number of guards at the bank for the `time` days **after** `i` are **non-decreasing**.

More formally, this means day `i` is a good day to rob the bank if and only if `security[i - time] >= security[i - time + 1] >= ... >= security[i] <= ... <= security[i + time - 1] <= security[i + time]`.

Return _a list of **all** days **(0-indexed)** that are good days to rob the bank_. _The order that the days are returned in does **not** matter._

**Example 1:**

**Input:** security = \[5,3,3,3,5,6,2\], time = 2
**Output:** \[2,3\]
**Explanation:**
On day 2, we have security\[0\] >= security\[1\] >= security\[2\] <= security\[3\] <= security\[4\].
On day 3, we have security\[1\] >= security\[2\] >= security\[3\] <= security\[4\] <= security\[5\].
No other days satisfy this condition, so days 2 and 3 are the only good days to rob the bank.

**Example 2:**

**Input:** security = \[1,1,1,1,1\], time = 0
**Output:** \[0,1,2,3,4\]
**Explanation:**
Since time equals 0, every day is a good day to rob the bank, so return every day.

**Example 3:**

**Input:** security = \[1,2,3,4,5,6\], time = 2
**Output:** \[\]
**Explanation:**
No day has 2 days before it that have a non-increasing number of guards.
Thus, no day is a good day to rob the bank, so return an empty list.

**Constraints:**

*   `1 <= security.length <= 105`
*   `0 <= security[i], time <= 105`

## A solution in Java

```java
long minNonZeroProduct(int p) {
    final long MOD = 1000000007;
    long prod = 1;
    long a = (1L << p) - 2;
    long b = ((1L << p) - 1) % MOD;

    while (a > 0) {
        if (a % 2 == 1) {
            prod = (prod * b) % MOD;
        }
        b = (b * b) % MOD;
        a /= 2;
    }
    return prod;
}
```
The given problem can be solved using the properties of binary numbers and modulo exponentiation.

1. Initialize a variable a with the value 2^p - 2 and b with the value (2^p - 1) % MOD, where p is the given integer and MOD is 10^9 + 7.
2. Initialize a variable prod with value 1 to store the product result.
3. Use a while loop to continue until the variable a becomes 0.
4. Inside the loop, check if a is an odd number. If it's odd, multiply prod by b, and take the result modulo MOD.
5. Update the value of b as (b * b) % MOD.
6. Divide the value of a by 2 for the next iteration.
7. After the loop, return the final value of the prod variable.

This algorithm optimizes the problem by leveraging modulo exponentiation for efficient computations. The time complexity is O(log(p)).

## A solution in C++

```cpp
long long minNonZeroProduct(int p) {
    const long long MOD = 1e9 + 7;
    long long prod = 1;
    long long a = (1LL << p) - 2;
    long long b = ((1LL << p) - 1) % MOD;

    while (a > 0) {
        if (a % 2) {
            prod = (prod * b) % MOD;
        }
        b = (b * b) % MOD;
        a /= 2;
    }
    return prod;
}
```
The given problem can be solved using the properties of binary numbers and modulo exponentiation.

1. Initialize a variable a with the value 2^p - 2 and b with the value (2^p - 1) % MOD, where p is the given integer and MOD is 10^9 + 7.
2. Initialize a variable prod with value 1 to store the product result.
3. Use a while loop to continue until the variable a becomes 0.
4. Inside the loop, check if a is an odd number. If it's odd, multiply prod by b, and take the result modulo MOD.
5. Update the value of b as (b * b) % MOD.
6. Divide the value of a by 2 for the next iteration.
7. After the loop, return the final value of the prod variable.

This algorithm optimizes the problem by leveraging modulo exponentiation for efficient computations. The time complexity is O(log(p)).

## A solution in Python

```python
def minNonZeroProduct(p):
    MOD = 10**9 + 7
    prod = 1
    a = (1 << p) - 2
    b = ((1 << p) - 1) % MOD

    while a > 0:
        if a % 2:
            prod = (prod * b) % MOD
        b = (b * b) % MOD
        a //= 2
    return prod
```
The given problem can be solved using the properties of binary numbers and modulo exponentiation.

1. Initialize a variable a with the value 2^p - 2 and b with the value (2^p - 1) % MOD, where p is the given integer and MOD is 10^9 + 7.
2. Initialize a variable prod with value 1 to store the product result.
3. Use a while loop to continue until the variable a becomes 0.
4. Inside the loop, check if a is an odd number. If it's odd, multiply prod by b, and take the result modulo MOD.
5. Update the value of b as (b * b) % MOD.
6. Divide the value of a by 2 for the next iteration.
7. After the loop, return the final value of the prod variable.

This algorithm optimizes the problem by leveraging modulo exponentiation for efficient computations. The time complexity is O(log(p)).

## A solution in Javascript

```javascript
function minNonZeroProduct(p) {
    const MOD = 1e9 + 7;
    let prod = 1;
    let a = (1n << BigInt(p)) - 2n;
    let b = ((1n << BigInt(p)) - 1n) % MOD;

    while (a > 0) {
        if (a % 2n == 1n) {
            prod = (prod * b) % MOD;
        }
        b = (b * b) % MOD;
        a /= 2n;
    }
    return prod;
}
```
The given problem can be solved using the properties of binary numbers and modulo exponentiation.

1. Initialize a variable a with the value 2^p - 2 and b with the value (2^p - 1) % MOD, where p is the given integer and MOD is 10^9 + 7.
2. Initialize a variable prod with value 1 to store the product result.
3. Use a while loop to continue until the variable a becomes 0.
4. Inside the loop, check if a is an odd number. If it's odd, multiply prod by b, and take the result modulo MOD.
5. Update the value of b as (b * b) % MOD.
6. Divide the value of a by 2 for the next iteration.
7. After the loop, return the final value of the prod variable.

This algorithm optimizes the problem by leveraging modulo exponentiation for efficient computations. The time complexity is O(log(p)).


# Detonate the Maximum Bombs

- slug: detonate-the-maximum-bombs
- difficulty: Medium

You are given a list of bombs. The **range** of a bomb is defined as the area where its effect can be felt. This area is in the shape of a **circle** with the center as the location of the bomb.

The bombs are represented by a **0-indexed** 2D integer array `bombs` where `bombs[i] = [xi, yi, ri]`. `xi` and `yi` denote the X-coordinate and Y-coordinate of the location of the `ith` bomb, whereas `ri` denotes the **radius** of its range.

You may choose to detonate a **single** bomb. When a bomb is detonated, it will detonate **all bombs** that lie in its range. These bombs will further detonate the bombs that lie in their ranges.

Given the list of `bombs`, return _the **maximum** number of bombs that can be detonated if you are allowed to detonate **only one** bomb_.

**Example 1:**

**Input:** bombs = \[\[2,1,3\],\[6,1,4\]\]
**Output:** 2
**Explanation:**
The above figure shows the positions and ranges of the 2 bombs.
If we detonate the left bomb, the right bomb will not be affected.
But if we detonate the right bomb, both bombs will be detonated.
So the maximum bombs that can be detonated is max(1, 2) = 2.

**Example 2:**

**Input:** bombs = \[\[1,1,5\],\[10,10,5\]\]
**Output:** 1
**Explanation:**
Detonating either bomb will not detonate the other bomb, so the maximum number of bombs that can be detonated is 1.

**Example 3:**

**Input:** bombs = \[\[1,2,3\],\[2,3,1\],\[3,4,2\],\[4,5,3\],\[5,6,4\]\]
**Output:** 5
**Explanation:**
The best bomb to detonate is bomb 0 because:
- Bomb 0 detonates bombs 1 and 2. The red circle denotes the range of bomb 0.
- Bomb 2 detonates bomb 3. The blue circle denotes the range of bomb 2.
- Bomb 3 detonates bomb 4. The green circle denotes the range of bomb 3.
Thus all 5 bombs are detonated.

**Constraints:**

*   `1 <= bombs.length <= 100`
*   `bombs[i].length == 3`
*   `1 <= xi, yi, ri <= 105`

## A solution in Java

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

class Solution {
    private boolean canReachBottom(int[][] grid, int row, int col) {
        if (row == grid.length - 1) return true;
        grid[row][col] = 1;

        int[] dr = {-1, 0, 1, 0};
        int[] dc = {0, 1, 0, -1};

        for (int i = 0; i < 4; ++i) {
            int nr = row + dr[i], nc = col + dc[i];
            if (nr >= 0 && nc >= 0 && nr < grid.length && nc < grid[0].length && grid[nr][nc] == 0) {
                if (canReachBottom(grid, nr, nc)) return true;
            }
        }
        return false;
    }

    public int latestDayToCross(int row, int col, int[][] cells) {
        int[][] grid = new int[row][col];
        int ans = 0;
        for (int i = 0; i < cells.length; ++i) {
            grid[cells[i][0] - 1][cells[i][1] - 1] = 1;

            boolean found = false;
            for (int j = 0; j < col; ++j) {
                if (grid[0][j] == 0 && canReachBottom(grid, 0, j)) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                ans = i;
                break;
            }
        }
        return ans;
    }
}
```
The algorithm starts by initializing a `grid` with the given dimensions filled with 0s. Then, for each day in `cells`, it sets the corresponding grid cell to 1 (water). After each day's cell is filled, the algorithm checks if there is still a path from the top row to the bottom row. This is done using a recursive depth-first search (`canReachBottom`) that checks in all four cardinal directions for an adjacent land cell (0). If a land cell is found, the search continues from the new cell. The search terminates if it reaches the bottom row, returning true, or if it cannot continue, returning false. The search is launched from each cell in the top row. If no path can be found, the algorithm stops and returns one less than the current day as the last day with a valid path.

## A solution in C++

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

bool canReachBottom(const std::vector<std::vector<int>>& grid, int row, int col) {
    if (row == grid.size() - 1) return true;
    grid[row][col] = 1;

    int dr[] = {-1, 0, 1, 0};
    int dc[] = {0, 1, 0, -1};

    for (int i = 0; i < 4; ++i) {
        int nr = row + dr[i], nc = col + dc[i];
        if (nr >= 0 && nc >= 0 && nr < grid.size() && nc < grid[0].size() && grid[nr][nc] == 0) {
            if (canReachBottom(grid, nr, nc)) return true;
        }
    }
    return false;
}

int latestDayToCross(int row, int col, std::vector<std::vector<int>>& cells) {
    std::vector<std::vector<int>> grid(row, std::vector<int>(col, 0));
    int ans = 0;
    for (int i = 0; i < cells.size(); ++i) {
        grid[cells[i][0] - 1][cells[i][1] - 1] = 1;

        bool found = false;
        for (int j = 0; j < col; ++j) {
            if (grid[0][j] == 0 && canReachBottom(grid, 0, j)) {
                found = true;
                break;
            }
        }

        if (!found) {
            ans = i;
            break;
        }
    }
    return ans;
}
```
The algorithm starts by initializing a `grid` with the given dimensions filled with 0s. Then, for each day in `cells`, it sets the corresponding grid cell to 1 (water). After each day's cell is filled, the algorithm checks if there is still a path from the top row to the bottom row. This is done using a recursive depth-first search (`canReachBottom`) that checks in all four cardinal directions for an adjacent land cell (0). If a land cell is found, the search continues from the new cell. The search terminates if it reaches the bottom row, returning true, or if it cannot continue, returning false. The search is launched from each cell in the top row. If no path can be found, the algorithm stops and returns one less than the current day as the last day with a valid path.

## A solution in Python

```python
def can_reach_bottom(grid, row, col):
    if row == len(grid) - 1:
        return True
    grid[row][col] = 1

    directions = [(-1, 0), (0, 1), (1, 0), (0, -1)]

    for dr, dc in directions:
        nr, nc = row + dr, col + dc
        if 0 <= nr < len(grid) and 0 <= nc < len(grid[0]) and grid[nr][nc] == 0:
            if can_reach_bottom(grid, nr, nc):
                return True

    return False

def latestDayToCross(row, col, cells):
    grid = [[0] * col for _ in range(row)]
    ans = 0

    for day, cell in enumerate(cells):
        grid[cell[0] - 1][cell[1] - 1] = 1

        found = False
        for j in range(col):
            if grid[0][j] == 0 and can_reach_bottom(grid, 0, j):
                found = True
                break

        if not found:
            ans = day
            break

    return ans
```
The algorithm starts by initializing a `grid` with the given dimensions filled with 0s. Then, for each day in `cells`, it sets the corresponding grid cell to 1 (water). After each day's cell is filled, the algorithm checks if there is still a path from the top row to the bottom row. This is done using a recursive depth-first search (`canReachBottom`) that checks in all four cardinal directions for an adjacent land cell (0). If a land cell is found, the search continues from the new cell. The search terminates if it reaches the bottom row, returning true, or if it cannot continue, returning false. The search is launched from each cell in the top row. If no path can be found, the algorithm stops and returns one less than the current day as the last day with a valid path.

## A solution in Javascript

```javascript
function canReachBottom(grid, row, col) {
    if (row === grid.length - 1) return true;
    grid[row][col] = 1;

    const directions = [[-1, 0], [0, 1], [1, 0], [0, -1]];

    for (const [dr, dc] of directions) {
        const nr = row + dr;
        const nc = col + dc;
        if (nr >= 0 && nc >= 0 && nr < grid.length && nc < grid[0].length && grid[nr][nc] === 0) {
            if (canReachBottom(grid, nr, nc)) return true;
        }
    }

    return false;
}

function latestDayToCross(row, col, cells) {
    const grid = Array.from({ length: row }, () => Array(col).fill(0));
    let ans = 0;

    for (const [i, cell] of cells.entries()) {
        grid[cell[0] - 1][cell[1] - 1] = 1;

        let found = false;
        for (let j = 0; j < col; ++j) {
            if (grid[0][j] === 0 && canReachBottom(grid, 0, j)) {
                found = true;
                break;
            }
        }

        if (!found) {
            ans = i;
            break;
        }
    }
    return ans;
}
```
The algorithm starts by initializing a `grid` with the given dimensions filled with 0s. Then, for each day in `cells`, it sets the corresponding grid cell to 1 (water). After each day's cell is filled, the algorithm checks if there is still a path from the top row to the bottom row. This is done using a recursive depth-first search (`canReachBottom`) that checks in all four cardinal directions for an adjacent land cell (0). If a land cell is found, the search continues from the new cell. The search terminates if it reaches the bottom row, returning true, or if it cannot continue, returning false. The search is launched from each cell in the top row. If no path can be found, the algorithm stops and returns one less than the current day as the last day with a valid path.


# Sequentially Ordinal Rank Tracker

- slug: sequentially-ordinal-rank-tracker
- difficulty: Hard

A scenic location is represented by its `name` and attractiveness `score`, where `name` is a **unique** string among all locations and `score` is an integer. Locations can be ranked from the best to the worst. The **higher** the score, the better the location. If the scores of two locations are equal, then the location with the **lexicographically smaller** name is better.

You are building a system that tracks the ranking of locations with the system initially starting with no locations. It supports:

*   **Adding** scenic locations, **one at a time**.
*   **Querying** the `ith` **best** location of **all locations already added**, where `i` is the number of times the system has been queried (including the current query).
    *   For example, when the system is queried for the `4th` time, it returns the `4th` best location of all locations already added.

Note that the test data are generated so that **at any time**, the number of queries **does not exceed** the number of locations added to the system.

Implement the `SORTracker` class:

*   `SORTracker()` Initializes the tracker system.
*   `void add(string name, int score)` Adds a scenic location with `name` and `score` to the system.
*   `string get()` Queries and returns the `ith` best location, where `i` is the number of times this method has been invoked (including this invocation).

**Example 1:**

**Input**
\[ "SORTracker ",  "add ",  "add ",  "get ",  "add ",  "get ",  "add ",  "get ",  "add ",  "get ",  "add ",  "get ",  "get "\]
\[\[\], \[ "bradford ", 2\], \[ "branford ", 3\], \[\], \[ "alps ", 2\], \[\], \[ "orland ", 2\], \[\], \[ "orlando ", 3\], \[\], \[ "alpine ", 2\], \[\], \[\]\]
**Output**
\[null, null, null,  "branford ", null,  "alps ", null,  "bradford ", null,  "bradford ", null,  "bradford ",  "orland "\]

**Explanation**
SORTracker tracker = new SORTracker(); // Initialize the tracker system.
tracker.add( "bradford ", 2); // Add location with name= "bradford " and score=2 to the system.
tracker.add( "branford ", 3); // Add location with name= "branford " and score=3 to the system.
tracker.get();              // The sorted locations, from best to worst, are: branford, bradford.
                            // Note that branford precedes bradford due to its **higher score** (3 > 2).
                            // This is the 1st time get() is called, so return the best location:  "branford ".
tracker.add( "alps ", 2);     // Add location with name= "alps " and score=2 to the system.
tracker.get();              // Sorted locations: branford, alps, bradford.
                            // Note that alps precedes bradford even though they have the same score (2).
                            // This is because  "alps " is **lexicographically smaller** than  "bradford ".
                            // Return the 2nd best location  "alps ", as it is the 2nd time get() is called.
tracker.add( "orland ", 2);   // Add location with name= "orland " and score=2 to the system.
tracker.get();              // Sorted locations: branford, alps, bradford, orland.
                            // Return  "bradford ", as it is the 3rd time get() is called.
tracker.add( "orlando ", 3);  // Add location with name= "orlando " and score=3 to the system.
tracker.get();              // Sorted locations: branford, orlando, alps, bradford, orland.
                            // Return  "bradford ".
tracker.add( "alpine ", 2);   // Add location with name= "alpine " and score=2 to the system.
tracker.get();              // Sorted locations: branford, orlando, alpine, alps, bradford, orland.
                            // Return  "bradford ".
tracker.get();              // Sorted locations: branford, orlando, alpine, alps, bradford, orland.
                            // Return  "orland ".

**Constraints:**

*   `name` consists of lowercase English letters, and is unique among all locations.
*   `1 <= name.length <= 10`
*   `1 <= score <= 105`
*   At any time, the number of calls to `get` does not exceed the number of calls to `add`.
*   At most `4 * 104` calls **in total** will be made to `add` and `get`.

## A solution in Java

```java
public int findMiddleIndex(int[] nums) {
    int total_sum = 0;
    for (int num : nums) total_sum += num;

    int left_sum = 0;
    for (int i = 0; i < nums.length; i++) {
        total_sum -= nums[i];
        if (left_sum == total_sum) return i;
        left_sum += nums[i];
    }

    return -1;
}
```
1. Calculate the total sum of the elements in the array.
2. Initialize a variable `left_sum` to store the sum of elements on the left side of middleIndex.
3. Iterate through the elements of the array:
    a. Subtract the current element from the total sum.
    b. Compare the left_sum with the total sum (which now represents the sum of the elements on the right side after excluding the current element). If they are equal, return the current index as the middleIndex.
    c. Add the current element to the left_sum.
4. If none of the indices satisfy the condition, return -1.

## A solution in C++

```cpp
int findMiddleIndex(vector<int>& nums) {
    int total_sum = 0;
    for (int num : nums) total_sum += num;

    int left_sum = 0;
    for (int i = 0; i < nums.size(); ++i) {
        total_sum -= nums[i];
        if (left_sum == total_sum) return i;
        left_sum += nums[i];
    }

    return -1;
}
```
1. Calculate the total sum of the elements in the array.
2. Initialize a variable `left_sum` to store the sum of elements on the left side of middleIndex.
3. Iterate through the elements of the array:
    a. Subtract the current element from the total sum.
    b. Compare the left_sum with the total sum (which now represents the sum of the elements on the right side after excluding the current element). If they are equal, return the current index as the middleIndex.
    c. Add the current element to the left_sum.
4. If none of the indices satisfy the condition, return -1.

## A solution in Python

```python
def findMiddleIndex(nums):
    total_sum = sum(nums)

    left_sum = 0
    for i, num in enumerate(nums):
        total_sum -= num
        if left_sum == total_sum:
            return i
        left_sum += num

    return -1
```
1. Calculate the total sum of the elements in the array.
2. Initialize a variable `left_sum` to store the sum of elements on the left side of middleIndex.
3. Iterate through the elements of the array:
    a. Subtract the current element from the total sum.
    b. Compare the left_sum with the total sum (which now represents the sum of the elements on the right side after excluding the current element). If they are equal, return the current index as the middleIndex.
    c. Add the current element to the left_sum.
4. If none of the indices satisfy the condition, return -1.

## A solution in Javascript

```javascript
function findMiddleIndex(nums) {
    let total_sum = nums.reduce((acc, num) => acc + num, 0);

    let left_sum = 0;
    for (let i = 0; i < nums.length; i++) {
        total_sum -= nums[i];
        if (left_sum === total_sum) return i;
        left_sum += nums[i];
    }

    return -1;
}
```
1. Calculate the total sum of the elements in the array.
2. Initialize a variable `left_sum` to store the sum of elements on the left side of middleIndex.
3. Iterate through the elements of the array:
    a. Subtract the current element from the total sum.
    b. Compare the left_sum with the total sum (which now represents the sum of the elements on the right side after excluding the current element). If they are equal, return the current index as the middleIndex.
    c. Add the current element to the left_sum.
4. If none of the indices satisfy the condition, return -1.


# Rings and Rods

- slug: rings-and-rods
- difficulty: Easy

There are `n` rings and each ring is either red, green, or blue. The rings are distributed **across ten rods** labeled from `0` to `9`.

You are given a string `rings` of length `2n` that describes the `n` rings that are placed onto the rods. Every two characters in `rings` forms a **color-position pair** that is used to describe each ring where:

*   The **first** character of the `ith` pair denotes the `ith` ring's **color** (`'R'`, `'G'`, `'B'`).
*   The **second** character of the `ith` pair denotes the **rod** that the `ith` ring is placed on (`'0'` to `'9'`).

For example, `"R3G2B1 "` describes `n == 3` rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1.

Return _the number of rods that have **all three colors** of rings on them._

**Example 1:**

**Input:** rings =  "B0B6G0R6R0R6G9 "
**Output:** 1
**Explanation:**
- The rod labeled 0 holds 3 rings with all colors: red, green, and blue.
- The rod labeled 6 holds 3 rings, but it only has red and blue.
- The rod labeled 9 holds only a green ring.
Thus, the number of rods with all three colors is 1.

**Example 2:**

**Input:** rings =  "B0R0G0R9R0B0G0 "
**Output:** 1
**Explanation:**
- The rod labeled 0 holds 6 rings with all colors: red, green, and blue.
- The rod labeled 9 holds only a red ring.
Thus, the number of rods with all three colors is 1.

**Example 3:**

**Input:** rings =  "G4 "
**Output:** 0
**Explanation:**
Only one ring is given. Thus, no rods have all three colors.

**Constraints:**

*   `rings.length == 2 * n`
*   `1 <= n <= 100`
*   `rings[i]` where `i` is **even** is either `'R'`, `'G'`, or `'B'` (**0-indexed**).
*   `rings[i]` where `i` is **odd** is a digit from `'0'` to `'9'` (**0-indexed**).

## A solution in Java

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

public List<List<Integer>> findFarmland(int[][] land) {
    int m = land.length, n = land[0].length;
    List<List<Integer>> res = new ArrayList<>();

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (land[i][j] == 1) {
                int r = i, c = j;
                while (r < m && land[r][j] == 1) ++r;
                while (c < n && land[i][c] == 1) ++c;
                for (int x = i; x < r; ++x) {
                    for (int y = j; y < c; ++y) {
                        land[x][y] = 0;
                    }
                }
                res.add(List.of(i, j, r - 1, c - 1));
            }
        }
    }

    return res;
}
```
1. Iterate over each cell (i, j) in the given land matrix.
2. If the cell value is 1 (farmland), initiate two pointers (r and c) at the current cell.
3. Move r downwards while the cells in the same column have value 1.
4. Move c rightwards while the cells in the same row have value 1.
5. Set all cells within the rectangle (i, j, r-1, c-1) to 0, and add [i, j, r-1, c-1] to the result list.
6. Repeat steps 1-5 for each cell in the land matrix.
7. Return the result list with coordinates for each group of farmland.

## A solution in C++

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

vector<vector<int>> findFarmland(vector<vector<int>>& land) {
    int m = land.size(), n = land[0].size();
    vector<vector<int>> res;

    for (int i = 0; i < m; ++i) {
        for (int j = 0; j < n; ++j) {
            if (land[i][j] == 1) {
                int r = i, c = j;
                while (r < m && land[r][j] == 1) ++r;
                while (c < n && land[i][c] == 1) ++c;
                for (int x = i; x < r; ++x) {
                    for (int y = j; y < c; ++y) {
                        land[x][y] = 0;
                    }
                }
                res.push_back({i, j, r - 1, c - 1});
            }
        }
    }

    return res;
}
```
1. Iterate over each cell (i, j) in the given land matrix.
2. If the cell value is 1 (farmland), initiate two pointers (r and c) at the current cell.
3. Move r downwards while the cells in the same column have value 1.
4. Move c rightwards while the cells in the same row have value 1.
5. Set all cells within the rectangle (i, j, r-1, c-1) to 0, and add [i, j, r-1, c-1] to the result list.
6. Repeat steps 1-5 for each cell in the land matrix.
7. Return the result list with coordinates for each group of farmland.

## A solution in Python

```python
def findFarmland(land):
    m, n = len(land), len(land[0])
    res = []

    for i in range(m):
        for j in range(n):
            if land[i][j] == 1:
                r, c = i, j
                while r < m and land[r][j] == 1: r += 1
                while c < n and land[i][c] == 1: c += 1
                for x in range(i, r):
                    for y in range(j,c):
                        land[x][y] = 0
                res.append([i, j, r - 1, c - 1])

    return res
```
1. Iterate over each cell (i, j) in the given land matrix.
2. If the cell value is 1 (farmland), initiate two pointers (r and c) at the current cell.
3. Move r downwards while the cells in the same column have value 1.
4. Move c rightwards while the cells in the same row have value 1.
5. Set all cells within the rectangle (i, j, r-1, c-1) to 0, and add [i, j, r-1, c-1] to the result list.
6. Repeat steps 1-5 for each cell in the land matrix.
7. Return the result list with coordinates for each group of farmland.

## A solution in Javascript

```javascript
function findFarmland(land) {
    const m = land.length, n = land[0].length;
    const res = [];

    for (let i = 0; i < m; ++i) {
        for (let j = 0; j < n; ++j) {
            if (land[i][j] === 1) {
                let r = i, c = j;
                while (r < m && land[r][j] === 1) ++r;
                while (c < n && land[i][c] === 1) ++c;
                for (let x = i; x < r; ++x) {
                    for (let y = j; y < c; ++y) {
                        land[x][y] = 0;
                    }
                }
                res.push([i, j, r - 1, c - 1]);
            }
        }
    }

    return res;
}
```
1. Iterate over each cell (i, j) in the given land matrix.
2. If the cell value is 1 (farmland), initiate two pointers (r and c) at the current cell.
3. Move r downwards while the cells in the same column have value 1.
4. Move c rightwards while the cells in the same row have value 1.
5. Set all cells within the rectangle (i, j, r-1, c-1) to 0, and add [i, j, r-1, c-1] to the result list.
6. Repeat steps 1-5 for each cell in the land matrix.
7. Return the result list with coordinates for each group of farmland.


# Sum of Subarray Ranges

- slug: sum-of-subarray-ranges
- difficulty: Medium

You are given an integer array `nums`. The **range** of a subarray of `nums` is the difference between the largest and smallest element in the subarray.

Return _the **sum of all** subarray ranges of_ `nums`_._

A subarray is a contiguous **non-empty** sequence of elements within an array.

**Example 1:**

**Input:** nums = \[1,2,3\]
**Output:** 4
**Explanation:** The 6 subarrays of nums are the following:
\[1\], range = largest - smallest = 1 - 1 = 0
\[2\], range = 2 - 2 = 0
\[3\], range = 3 - 3 = 0
\[1,2\], range = 2 - 1 = 1
\[2,3\], range = 3 - 2 = 1
\[1,2,3\], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 1 + 1 + 2 = 4.

**Example 2:**

**Input:** nums = \[1,3,3\]
**Output:** 4
**Explanation:** The 6 subarrays of nums are the following:
\[1\], range = largest - smallest = 1 - 1 = 0
\[3\], range = 3 - 3 = 0
\[3\], range = 3 - 3 = 0
\[1,3\], range = 3 - 1 = 2
\[3,3\], range = 3 - 3 = 0
\[1,3,3\], range = 3 - 1 = 2
So the sum of all ranges is 0 + 0 + 0 + 2 + 0 + 2 = 4.

**Example 3:**

**Input:** nums = \[4,-2,-3,4,1\]
**Output:** 59
**Explanation:** The sum of all subarray ranges of nums is 59.

**Constraints:**

*   `1 <= nums.length <= 1000`
*   `-109 <= nums[i] <= 109`

**Follow-up:** Could you find a solution with `O(n)` time complexity?

## A solution in Java

```java
import java.util.*;

class LockingTree {
    int[] parent;
    List<Set<Integer>> children;
    int[] locks;

    public LockingTree(int[] parent) {
        this.parent = parent;
        children = new ArrayList<>(parent.length);
        locks = new int[parent.length];
        Arrays.fill(locks, -1);
        for(int i = 0; i < parent.length; i++)
            children.add(new HashSet<>());
        for(int i = 1; i < parent.length; i++)
            children.get(parent[i]).add(i);
    }

    public boolean lock(int num, int user) {
        if(locks[num] == -1) {
            locks[num] = user;
            return true;
        }
        return false;
    }

    public boolean unlock(int num, int user) {
        if(locks[num] == user) {
            locks[num] = -1;
            return true;
        }
        return false;
    }

    public boolean upgrade(int num, int user) {
        if(locks[num] != -1) return false;

        int cur = num;
        while(cur != -1) {
            if(locks[cur] != -1) return false;
            cur = parent[cur];
        }

        boolean lockedDescendant = hasLockedDescendants(num);
        if(lockedDescendant) {
            locks[num] = user;
        }
        return lockedDescendant;
    }

    private boolean hasLockedDescendants(int node) {
        boolean lockedDescendant = false;
        for(int child : children.get(node)) {
            if(locks[child] != -1) {
                lockedDescendant = true;
                locks[child] = -1;
            }
            lockedDescendant |= hasLockedDescendants(child);
        }
        return lockedDescendant;
    }
}
```
The algorithm is the same for all languages. For each node, we store the parent and the children, and an array to keep track of the locks:

- In the `lock` function, we check if the node is not locked. If it is not locked, we lock it with the user and return true. Otherwise, return false.
- In the `unlock` function, we check if the node is locked by the user. If so, we unlock it and return true. Otherwise, return false.
- In the `upgrade` function, we first check if the node is locked; if so, return false. Then, we check if the node itself or any of its ancestors have locks; if so, return false. Finally, we check if any descendant of the node has a lock (using a recursive function); if so, we unlock the descendants, lock the node, and return true. If no descendant is locked, return false.

## A solution in C++

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

using namespace std;

class LockingTree {
public:
    vector<int> parent;
    vector<unordered_set<int>> children;
    vector<int> locks;

    LockingTree(vector<int>& parent) : parent(parent) {
        children.resize(parent.size());
        locks.resize(parent.size(), -1);
        for(int i = 1; i < parent.size(); i++)
            children[parent[i]].insert(i);
    }

    bool lock(int num, int user) {
        if(locks[num] == -1) {
            locks[num] = user;
            return true;
        }
        return false;
    }

    bool unlock(int num, int user) {
        if(locks[num] == user) {
            locks[num] = -1;
            return true;
        }
        return false;
    }

    bool upgrade(int num, int user) {
        if(locks[num] != -1) return false;

        int cur = num;
        while(cur != -1) {
            if(locks[cur] != -1) return false;
            cur = parent[cur];
        }

        bool locked_descendant = false;
        function<bool(int)> has_locked_descendants = [&](int node) {
            for(int child : children[node]) {
                if(locks[child] != -1) {
                    locked_descendant = true;
                    locks[child] = -1;
                }
                has_locked_descendants(child);
            }
            return locked_descendant;
        };

        if(has_locked_descendants(num)) {
            locks[num] = user;
            return true;
        }
        return false;
    }
};
```
The algorithm is the same for all languages. For each node, we store the parent and the children, and an array to keep track of the locks:

- In the `lock` function, we check if the node is not locked. If it is not locked, we lock it with the user and return true. Otherwise, return false.
- In the `unlock` function, we check if the node is locked by the user. If so, we unlock it and return true. Otherwise, return false.
- In the `upgrade` function, we first check if the node is locked; if so, return false. Then, we check if the node itself or any of its ancestors have locks; if so, return false. Finally, we check if any descendant of the node has a lock (using a recursive function); if so, we unlock the descendants, lock the node, and return true. If no descendant is locked, return false.

## A solution in Python

```python
from collections import defaultdict

class LockingTree:

    def __init__(self, parent):
        self.parent = parent
        self.children = defaultdict(set)
        self.locks = [-1] * len(parent)
        for i in range(1, len(parent)):
            self.children[parent[i]].add(i)

    def lock(self, num, user):
        if self.locks[num] == -1:
            self.locks[num] = user
            return True
        return False

    def unlock(self, num, user):
        if self.locks[num] == user:
            self.locks[num] = -1
            return True
        return False

    def upgrade(self, num, user):
        if self.locks[num] != -1: return False

        cur = num
        while cur != -1:
            if self.locks[cur] != -1: return False
            cur = self.parent[cur]

        locked_descendant = self._has_locked_descendants(num)
        if locked_descendant:
            self.locks[num] = user
        return locked_descendant

    def _has_locked_descendants(self, node):
        locked_descendant = False
        for child in self.children[node]:
            if self.locks[child] != -1:
                locked_descendant = True
                self.locks[child] = -1
            locked_descendant |= self._has_locked_descendants(child)
        return locked_descendant
```
The algorithm is the same for all languages. For each node, we store the parent and the children, and an array to keep track of the locks:

- In the `lock` function, we check if the node is not locked. If it is not locked, we lock it with the user and return true. Otherwise, return false.
- In the `unlock` function, we check if the node is locked by the user. If so, we unlock it and return true. Otherwise, return false.
- In the `upgrade` function, we first check if the node is locked; if so, return false. Then, we check if the node itself or any of its ancestors have locks; if so, return false. Finally, we check if any descendant of the node has a lock (using a recursive function); if so, we unlock the descendants, lock the node, and return true. If no descendant is locked, return false.

## A solution in Javascript

```javascript
class LockingTree {
    constructor(parent) {
        this.parent = parent;
        this.children = Array(parent.length).fill().map(() => new Set());
        this.locks = Array(parent.length).fill(-1);
        for(let i = 1; i < parent.length; i++)
            this.children[parent[i]].add(i);
    }

    lock(num, user) {
        if(this.locks[num] === -1) {
            this.locks[num] = user;
            return true;
        }
        return false;
    }

    unlock(num, user) {
        if(this.locks[num] === user) {
            this.locks[num] = -1;
            return true;
        }
        return false;
    }

    upgrade(num, user) {
        if(this.locks[num] !== -1) return false;

        let cur = num;
        while(cur !== -1) {
            if(this.locks[cur] !== -1) return false;
            cur = this.parent[cur];
        }

        const lockedDescendant = this._hasLockedDescendants(num);
        if(lockedDescendant) {
            this.locks[num] = user;
        }
        return lockedDescendant;
    }

    _hasLockedDescendants(node) {
        let lockedDescendant = false;
        for(const child of this.children[node]) {
            if(this.locks[child] !== -1) {
                lockedDescendant = true;
                this.locks[child] = -1;
            }
            lockedDescendant = lockedDescendant || this._hasLockedDescendants(child);
        }
        return lockedDescendant;
    }
}
```
The algorithm is the same for all languages. For each node, we store the parent and the children, and an array to keep track of the locks:

- In the `lock` function, we check if the node is not locked. If it is not locked, we lock it with the user and return true. Otherwise, return false.
- In the `unlock` function, we check if the node is locked by the user. If so, we unlock it and return true. Otherwise, return false.
- In the `upgrade` function, we first check if the node is locked; if so, return false. Then, we check if the node itself or any of its ancestors have locks; if so, return false. Finally, we check if any descendant of the node has a lock (using a recursive function); if so, we unlock the descendants, lock the node, and return true. If no descendant is locked, return false.


# Watering Plants II

- slug: watering-plants-ii
- difficulty: Medium

Alice and Bob want to water `n` plants in their garden. The plants are arranged in a row and are labeled from `0` to `n - 1` from left to right where the `ith` plant is located at `x = i`.

Each plant needs a specific amount of water. Alice and Bob have a watering can each, **initially full**. They water the plants in the following way:

*   Alice waters the plants in order from **left to right**, starting from the `0th` plant. Bob waters the plants in order from **right to left**, starting from the `(n - 1)th` plant. They begin watering the plants **simultaneously**.
*   It takes the same amount of time to water each plant regardless of how much water it needs.
*   Alice/Bob **must** water the plant if they have enough in their can to **fully** water it. Otherwise, they **first** refill their can (instantaneously) then water the plant.
*   In case both Alice and Bob reach the same plant, the one with **more** water currently in his/her watering can should water this plant. If they have the same amount of water, then Alice should water this plant.

Given a **0-indexed** integer array `plants` of `n` integers, where `plants[i]` is the amount of water the `ith` plant needs, and two integers `capacityA` and `capacityB` representing the capacities of Alice's and Bob's watering cans respectively, return _the **number of times** they have to refill to water all the plants_.

**Example 1:**

**Input:** plants = \[2,2,3,3\], capacityA = 5, capacityB = 5
**Output:** 1
**Explanation:**
- Initially, Alice and Bob have 5 units of water each in their watering cans.
- Alice waters plant 0, Bob waters plant 3.
- Alice and Bob now have 3 units and 2 units of water respectively.
- Alice has enough water for plant 1, so she waters it. Bob does not have enough water for plant 2, so he refills his can then waters it.
So, the total number of times they have to refill to water all the plants is 0 + 0 + 1 + 0 = 1.

**Example 2:**

**Input:** plants = \[2,2,3,3\], capacityA = 3, capacityB = 4
**Output:** 2
**Explanation:**
- Initially, Alice and Bob have 3 units and 4 units of water in their watering cans respectively.
- Alice waters plant 0, Bob waters plant 3.
- Alice and Bob now have 1 unit of water each, and need to water plants 1 and 2 respectively.
- Since neither of them have enough water for their current plants, they refill their cans and then water the plants.
So, the total number of times they have to refill to water all the plants is 0 + 1 + 1 + 0 = 2.

**Example 3:**

**Input:** plants = \[5\], capacityA = 10, capacityB = 8
**Output:** 0
**Explanation:**
- There is only one plant.
- Alice's watering can has 10 units of water, whereas Bob's can has 8 units. Since Alice has more water in her can, she waters this plant.
So, the total number of times they have to refill is 0.

**Constraints:**

*   `n == plants.length`
*   `1 <= n <= 105`
*   `1 <= plants[i] <= 106`
*   `max(plants[i]) <= capacityA, capacityB <= 109`

## A solution in Java

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

public class Solution {
    final int MOD = 1000000007;

    boolean isPrime(int n) {
        if (n <= 1) return false;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }

    public int numberOfGoodSubsets(int[] nums) {
        List<Integer> primes = new ArrayList<>();
        for (int i = 2; i <= 90; i++) {
            if (isPrime(i)) primes.add(i);
        }

        int[] cnt = new int[100];
        Arrays.fill(cnt, 0);
        for (int n : nums) cnt[n]++;

        long[] dp = new long[1 << 20];
        dp[0] = 1;

        for (int i = 30; i > 0; i--) {
            if (cnt[i] == 0) continue;
            List<Integer> mask = new ArrayList<>();
            for (int j : primes) {
                if (i % j == 0) {
                    mask.add(j);
                    while (i % j == 0) i /= j;
                }
            }
            if (i > 1) continue;

            int m = 0;
            for (int j : mask) m |= 1 << (j - 2);

            for (int j = dp.length - 1; j >= 0; j--) {
                if (dp[j] == 0) continue;
                long cur = 1;
                for (int k = 0; k < cnt[m]; k++) {
                    cur = (cur * 2) % MOD;
                    dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD;
                }
            }
        }

        long ans = 0;
        for (long n : dp) ans = (ans + n) % MOD;

        ans = (ans - dp[0] + MOD) % MOD;
        return (int) ((ans * (1L << (cnt[1] - 1))) % MOD);
    }
}
```
1. First, we create a list of prime numbers up to 90 using the isPrime function.
2. Then, we count the occurrence of each number in the provided 'nums' array and write it into the 'cnt' array.
3. Initialize a dp array of size 2^20, setting dp[0] to 1.
4. Iterate over the numbers from 30 to 1. Skip the ones with a count of 0.
5. Create a bitmask 'm' to store the prime factors of the number 'i' shifted by 1.
6. Iterate over the dp array from right to left. Skip the zeros.
7. Set 'cur' to 1 and multiply it by 2 for each 'cnt[m]', then update dp[j | m] according to the formula dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD.
8. Calculate the answer as the sum of the dp array, then subtract the initial dp[0] value and add MOD to it, and finally multiply by (1 << (cnt[1] - 1)).
9. Return the answer modulo MOD.

## A solution in C++

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

const int MOD = 1e9 + 7;

bool isPrime(int n) {
    if (n <= 1) return false;
    for (int i = 2; i*i <= n; i++) {
        if (n%i == 0) return false;
    }
    return true;
}

int numberOfGoodSubsets(std::vector<int>& nums) {
    std::unordered_set<int> primes;
    for (int i = 2; i <= 90; i++) {
        if (isPrime(i)) primes.insert(i);
    }

    std::vector<int> cnt(100, 0);
    for (auto n : nums) cnt[n]++;

    std::vector<long long> dp(1<<20, 0);
    dp[0] = 1;

    for (int i = 30; i > 0; i--) {
        if (cnt[i] == 0) continue;
        std::vector<int> mask;
        for (int j : primes) {
            if (i % j == 0) {
                mask.push_back(j);
                while (i % j == 0) i /= j;
            }
        }
        if (i > 1) continue;

        int m = 0;
        for (int j : mask) m |= 1<<(j-2);

        for (int j = dp.size()-1; j >= 0; --j) {
            if (dp[j] == 0) continue;
            long long cur = 1;
            for (int k = 0; k < cnt[m]; ++k) {
                cur = (cur * 2) % MOD;
                dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD;
            }
        }
    }

    long long ans = 0;
    for (long long n : dp) ans = (ans + n) % MOD;

    ans = (ans - dp[0] + MOD) % MOD;
    return (ans * (1 << (cnt[1] - 1))) % MOD;
}
```
1. First, we create a list of prime numbers up to 90 using the isPrime function.
2. Then, we count the occurrence of each number in the provided 'nums' array and write it into the 'cnt' array.
3. Initialize a dp array of size 2^20, setting dp[0] to 1.
4. Iterate over the numbers from 30 to 1. Skip the ones with a count of 0.
5. Create a bitmask 'm' to store the prime factors of the number 'i' shifted by 1.
6. Iterate over the dp array from right to left. Skip the zeros.
7. Set 'cur' to 1 and multiply it by 2 for each 'cnt[m]', then update dp[j | m] according to the formula dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD.
8. Calculate the answer as the sum of the dp array, then subtract the initial dp[0] value and add MOD to it, and finally multiply by (1 << (cnt[1] - 1)).
9. Return the answer modulo MOD.

## A solution in Python

```python
def numberOfGoodSubsets(nums: list[int]) -> int:
    MOD = 10**9 + 7

    def is_prime(n: int) -> bool:
        if n <= 1:
            return False
        for i in range(2, int(n**0.5) + 1):
            if n % i == 0:
                return False
        return True

    primes = [i for i in range(2, 91) if is_prime(i)]
    cnt = [0] * 100
    for n in nums:
        cnt[n] += 1

    dp = [0] * (1 << 20)
    dp[0] = 1

    for i in range(30, 0, -1):
        if cnt[i] == 0:
            continue
        mask = [j for j in primes if i % j == 0]
        i = i // j
        if i > 1:
            continue

        m = 0
        for j in mask:
            m |= 1 << (j - 2)

        for j in range(len(dp)-1, -1, -1):
            if dp[j] == 0:
                continue
            cur = 1
            for k in range(cnt[m]):
                cur = (cur * 2) % MOD
                dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD

    ans = sum(dp) % MOD
    ans = (ans - dp[0] + MOD) % MOD
    return (ans * (1 << (cnt[1] - 1))) % MOD
```
1. First, we create a list of prime numbers up to 90 using the isPrime function.
2. Then, we count the occurrence of each number in the provided 'nums' array and write it into the 'cnt' array.
3. Initialize a dp array of size 2^20, setting dp[0] to 1.
4. Iterate over the numbers from 30 to 1. Skip the ones with a count of 0.
5. Create a bitmask 'm' to store the prime factors of the number 'i' shifted by 1.
6. Iterate over the dp array from right to left. Skip the zeros.
7. Set 'cur' to 1 and multiply it by 2 for each 'cnt[m]', then update dp[j | m] according to the formula dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD.
8. Calculate the answer as the sum of the dp array, then subtract the initial dp[0] value and add MOD to it, and finally multiply by (1 << (cnt[1] - 1)).
9. Return the answer modulo MOD.

## A solution in Javascript

```javascript
function numberOfGoodSubsets(nums) {
    const MOD = 1e9 + 7;

    function isPrime(n) {
        if (n <= 1) return false;
        for (let i = 2; i ** 2 <= n; i++) {
            if (n % i === 0) return false;
        }
        return true;
    }

    const primes = [];
    for (let i = 2; i <= 90; i++) {
        if (isPrime(i)) primes.push(i);
    }

    const cnt = Array(100).fill(0);
    nums.forEach(n => cnt[n]++);

    const dp = Array(1 << 20).fill(0);
    dp[0] = 1;

    for (let i = 30; i > 0; i--) {
        if (cnt[i] === 0) continue;
        const mask = [];
        primes.forEach(j => {
            if (i % j === 0) {
                mask.push(j);
                while (i % j === 0) i /= j;
            }
        });
        if (i > 1) continue;

        let m = 0;
        mask.forEach(j => m |= 1 << (j - 2));

        for (let j = dp.length - 1; j >= 0; j--) {
            if (dp[j] === 0) continue;
            let cur = 1;
            for (let k = 0; k < cnt[m]; k++) {
                cur = (cur * 2) % MOD;
                dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD;
            }
        }
    }

    let ans = 0;
    dp.forEach(n => ans = (ans + n) % MOD);

    ans = (ans - dp[0] + MOD) % MOD;
    return (ans * (1 << (cnt[1] - 1))) % MOD;
}
```
1. First, we create a list of prime numbers up to 90 using the isPrime function.
2. Then, we count the occurrence of each number in the provided 'nums' array and write it into the 'cnt' array.
3. Initialize a dp array of size 2^20, setting dp[0] to 1.
4. Iterate over the numbers from 30 to 1. Skip the ones with a count of 0.
5. Create a bitmask 'm' to store the prime factors of the number 'i' shifted by 1.
6. Iterate over the dp array from right to left. Skip the zeros.
7. Set 'cur' to 1 and multiply it by 2 for each 'cnt[m]', then update dp[j | m] according to the formula dp[j | m] = (dp[j | m] + dp[j] * cur) % MOD.
8. Calculate the answer as the sum of the dp array, then subtract the initial dp[0] value and add MOD to it, and finally multiply by (1 << (cnt[1] - 1)).
9. Return the answer modulo MOD.


# Maximum Fruits Harvested After at Most K Steps

- slug: maximum-fruits-harvested-after-at-most-k-steps
- difficulty: Hard

Fruits are available at some positions on an infinite x-axis. You are given a 2D integer array `fruits` where `fruits[i] = [positioni, amounti]` depicts `amounti` fruits at the position `positioni`. `fruits` is already **sorted** by `positioni` in **ascending order**, and each `positioni` is **unique**.

You are also given an integer `startPos` and an integer `k`. Initially, you are at the position `startPos`. From any position, you can either walk to the **left or right**. It takes **one step** to move **one unit** on the x-axis, and you can walk **at most** `k` steps in total. For every position you reach, you harvest all the fruits at that position, and the fruits will disappear from that position.

Return _the **maximum total number** of fruits you can harvest_.

**Example 1:**

**Input:** fruits = \[\[2,8\],\[6,3\],\[8,6\]\], startPos = 5, k = 4
**Output:** 9
**Explanation:**
The optimal way is to:
- Move right to position 6 and harvest 3 fruits
- Move right to position 8 and harvest 6 fruits
You moved 3 steps and harvested 3 + 6 = 9 fruits in total.

**Example 2:**

**Input:** fruits = \[\[0,9\],\[4,1\],\[5,7\],\[6,2\],\[7,4\],\[10,9\]\], startPos = 5, k = 4
**Output:** 14
**Explanation:**
You can move at most k = 4 steps, so you cannot reach position 0 nor 10.
The optimal way is to:
- Harvest the 7 fruits at the starting position 5
- Move left to position 4 and harvest 1 fruit
- Move right to position 6 and harvest 2 fruits
- Move right to position 7 and harvest 4 fruits
You moved 1 + 3 = 4 steps and harvested 7 + 1 + 2 + 4 = 14 fruits in total.

**Example 3:**

**Input:** fruits = \[\[0,3\],\[6,4\],\[8,5\]\], startPos = 3, k = 2
**Output:** 0
**Explanation:**
You can move at most k = 2 steps and cannot reach any position with fruits.

**Constraints:**

*   `1 <= fruits.length <= 105`
*   `fruits[i].length == 2`
*   `0 <= startPos, positioni <= 2 * 105`
*   `positioni-1 < positioni` for any `i > 0` (**0-indexed**)
*   `1 <= amounti <= 104`
*   `0 <= k <= 2 * 105`

## A solution in Java

```java
import java.util.Arrays;

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

public int findGCD(int[] nums) {
    int minVal = Arrays.stream(nums).min().getAsInt();
    int maxVal = Arrays.stream(nums).max().getAsInt();
    return gcd(minVal, maxVal);
}
```
The algorithm implementation follows these steps:

1. Define the gcd() function, which will compute the greatest common divisor using the Euclidean algorithm.
2. Create the findGCD() function, which takes an array of integers (nums) as an argument.
3. In the findGCD() function, find the minimum and maximum values in the given array. This is done using various min/max methods depending on the language used: std::min_element/std::max_element (C++), Arrays.stream (Java), min/max (Python), or. Math.min/Math.max (JavaScript).
4. Return the gcd of the minimum and maximum values found in step 3 by calling the gcd() function.

This finds the greatest common divisor of the smallest and largest numbers in the given array.

## A solution in C++

```cpp
#include <algorithm>

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

int findGCD(std::vector<int>& nums) {
    int minVal = *std::min_element(nums.begin(), nums.end());
    int maxVal = *std::max_element(nums.begin(), nums.end());
    return gcd(minVal, maxVal);
}
```
The algorithm implementation follows these steps:

1. Define the gcd() function, which will compute the greatest common divisor using the Euclidean algorithm.
2. Create the findGCD() function, which takes an array of integers (nums) as an argument.
3. In the findGCD() function, find the minimum and maximum values in the given array. This is done using various min/max methods depending on the language used: std::min_element/std::max_element (C++), Arrays.stream (Java), min/max (Python), or. Math.min/Math.max (JavaScript).
4. Return the gcd of the minimum and maximum values found in step 3 by calling the gcd() function.

This finds the greatest common divisor of the smallest and largest numbers in the given array.

## A solution in Python

```python
from math import gcd

def findGCD(nums):
    return gcd(min(nums), max(nums))
```
The algorithm implementation follows these steps:

1. Define the gcd() function, which will compute the greatest common divisor using the Euclidean algorithm.
2. Create the findGCD() function, which takes an array of integers (nums) as an argument.
3. In the findGCD() function, find the minimum and maximum values in the given array. This is done using various min/max methods depending on the language used: std::min_element/std::max_element (C++), Arrays.stream (Java), min/max (Python), or. Math.min/Math.max (JavaScript).
4. Return the gcd of the minimum and maximum values found in step 3 by calling the gcd() function.

This finds the greatest common divisor of the smallest and largest numbers in the given array.

## A solution in Javascript

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

function findGCD(nums) {
    const minVal = Math.min(...nums);
    const maxVal = Math.max(...nums);
    return gcd(minVal, maxVal);
}
```
The algorithm implementation follows these steps:

1. Define the gcd() function, which will compute the greatest common divisor using the Euclidean algorithm.
2. Create the findGCD() function, which takes an array of integers (nums) as an argument.
3. In the findGCD() function, find the minimum and maximum values in the given array. This is done using various min/max methods depending on the language used: std::min_element/std::max_element (C++), Arrays.stream (Java), min/max (Python), or. Math.min/Math.max (JavaScript).
4. Return the gcd of the minimum and maximum values found in step 3 by calling the gcd() function.

This finds the greatest common divisor of the smallest and largest numbers in the given array.


# Number of Unique Flavors After Sharing K Candies

- slug: number-of-unique-flavors-after-sharing-k-candies
- difficulty: Medium

You are given a **0-indexed** integer array `candies`, where `candies[i]` represents the flavor of the `ith` candy. Your mom wants you to share these candies with your little sister by giving her `k` **consecutive** candies, but you want to keep as many flavors of candies as possible.

Return _the **maximum** number of **unique** flavors of candy you can keep after sharing_ _with your sister._

**Example 1:**

**Input:** candies = \[1,2,2,3,4,3\], k = 3
**Output:** 3
**Explanation:**
Give the candies in the range \[1, 3\] (inclusive) with flavors \[2,2,3\].
You can eat candies with flavors \[1,4,3\].
There are 3 unique flavors, so return 3.

**Example 2:**

**Input:** candies = \[2,2,2,2,3,3\], k = 2
**Output:** 2
**Explanation:**
Give the candies in the range \[3, 4\] (inclusive) with flavors \[2,3\].
You can eat candies with flavors \[2,2,2,3\].
There are 2 unique flavors, so return 2.
Note that you can also share the candies with flavors \[2,2\] and eat the candies with flavors \[2,2,3,3\].

**Example 3:**

**Input:** candies = \[2,4,5\], k = 0
**Output:** 3
**Explanation:**
You do not have to give any candies.
You can eat the candies with flavors \[2,4,5\].
There are 3 unique flavors, so return 3.

**Constraints:**

*   `1 <= candies.length <= 105`
*   `1 <= candies[i] <= 105`
*   `0 <= k <= candies.length`

## A solution in Java

```java
public String findDifferentBinaryString(String[] nums) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < nums.length; i++) {
        result.append(nums[i].charAt(i) == '0' ? '1' : '0');
    }
    return result.toString();
}
```
The algorithm iterates through the array of strings `nums` and creates a new binary string `result` by following this rule for each character at position i: if the character in the original string at position i is '0', add '1' to the result; otherwise, add '0'. This way, the resulting string will differ from every binary string in the input array in at least one position.

## A solution in C++

```cpp
std::string findDifferentBinaryString(std::vector<std::string>& nums) {
    std::string result;
    for (int i = 0; i < nums.size(); i++) {
        result.push_back(nums[i][i] == '0' ? '1' : '0');
    }
    return result;
}
```
The algorithm iterates through the array of strings `nums` and creates a new binary string `result` by following this rule for each character at position i: if the character in the original string at position i is '0', add '1' to the result; otherwise, add '0'. This way, the resulting string will differ from every binary string in the input array in at least one position.

## A solution in Python

```python
def find_different_binary_string(nums):
    return "".join("1" if nums[i][i] == "0" else "0" for i in range(len(nums)))
```
The algorithm iterates through the array of strings `nums` and creates a new binary string `result` by following this rule for each character at position i: if the character in the original string at position i is '0', add '1' to the result; otherwise, add '0'. This way, the resulting string will differ from every binary string in the input array in at least one position.

## A solution in Javascript

```javascript
function findDifferentBinaryString(nums) {
    let result = "";
    for (let i = 0; i < nums.length; i++) {
        result += nums[i][i] === '0' ? '1' : '0';
    }
    return result;
}
```
The algorithm iterates through the array of strings `nums` and creates a new binary string `result` by following this rule for each character at position i: if the character in the original string at position i is '0', add '1' to the result; otherwise, add '0'. This way, the resulting string will differ from every binary string in the input array in at least one position.


# Find First Palindromic String in the Array

- slug: find-first-palindromic-string-in-the-array
- difficulty: Easy

Given an array of strings `words`, return _the first **palindromic** string in the array_. If there is no such string, return _an **empty string**_ `" "`.

A string is **palindromic** if it reads the same forward and backward.

**Example 1:**

**Input:** words = \[ "abc ", "car ", "ada ", "racecar ", "cool "\]
**Output:**  "ada "
**Explanation:** The first string that is palindromic is  "ada ".
Note that  "racecar " is also palindromic, but it is not the first.

**Example 2:**

**Input:** words = \[ "notapalindrome ", "racecar "\]
**Output:**  "racecar "
**Explanation:** The first and only string that is palindromic is  "racecar ".

**Example 3:**

**Input:** words = \[ "def ", "ghi "\]
**Output:**  " "
**Explanation:** There are no palindromic strings, so the empty string is returned.

**Constraints:**

*   `1 <= words.length <= 100`
*   `1 <= words[i].length <= 100`
*   `words[i]` consists only of lowercase English letters.

## A solution in Java

```java
class Solution {
    public int minimizeTheDifference(int[][] mat, int target) {
        int m = mat.length, n = mat[0].length;
        int[] dp = new int[4901], new_dp = new int[4901];
        dp[0] = 1;
        for (int i = 0; i < m; ++i) {
            Arrays.fill(new_dp, 0);
            for (int j = 0; j < n; ++j) {
                for (int k = 0; k + mat[i][j] < 4901; ++k) {
                    new_dp[k + mat[i][j]] |= dp[k];
                }
            }
            int[] temp = dp;
            dp = new_dp;
            new_dp = temp;
        }
        for (int i = 0; i < 4901; ++i) {
            if (dp[i] > 0) return Math.abs(target - i);
        }
        return Integer.MAX_VALUE;
    }
}
```
The given problem is a variation of the subset sum problem. Instead of checking all combinations using backtracking, we can use dynamic programming to optimize it. We use an array `dp` of size 4901 to store whether a sum value is possible or not.

1. Initialize the `dp` array with 0, except `dp[0] = 1`, which means sum 0 is possible.
2. For each row in the matrix, we create a temporary `new_dp` array and loop through all columns.
3. For each column, iterate through the `dp` array, and if `dp[k] = 1`, set `new_dp[k + mat[i][j]] = 1`. It means the sum `k + mat[i][j]` is possible based on the current `dp`.
4. Swap `dp` and `new_dp` arrays for the next iteration.
5. After iterating through all rows, go through `dp`, if `dp[i] = 1`, return the absolute difference between i and the target.
6. If we didn't find a possible sum, return the maximum possible absolute difference.

The algorithm's time complexity is O(m * n * 4900) and space complexity is O(4901).

## A solution in C++

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

int minimizeTheDifference(vector<vector<int>>& mat, int target) {
    int m = mat.size(), n = mat[0].size();
    vector<int> dp(4901, 0), new_dp(4901, 0);
    dp[0] = 1;
    for (int i = 0; i < m; ++i) {
        fill(new_dp.begin(), new_dp.end(), 0);
        for (int j = 0; j < n; ++j) {
            for (int k = 0; k + mat[i][j] < 4901; ++k) {
                new_dp[k + mat[i][j]] |= dp[k];
            }
        }
        dp.swap(new_dp);
    }
    for (int i = 0; i < 4901; ++i) {
        if (dp[i]) return abs(target - i);
    }
    return INT_MAX;
}
```
The given problem is a variation of the subset sum problem. Instead of checking all combinations using backtracking, we can use dynamic programming to optimize it. We use an array `dp` of size 4901 to store whether a sum value is possible or not.

1. Initialize the `dp` array with 0, except `dp[0] = 1`, which means sum 0 is possible.
2. For each row in the matrix, we create a temporary `new_dp` array and loop through all columns.
3. For each column, iterate through the `dp` array, and if `dp[k] = 1`, set `new_dp[k + mat[i][j]] = 1`. It means the sum `k + mat[i][j]` is possible based on the current `dp`.
4. Swap `dp` and `new_dp` arrays for the next iteration.
5. After iterating through all rows, go through `dp`, if `dp[i] = 1`, return the absolute difference between i and the target.
6. If we didn't find a possible sum, return the maximum possible absolute difference.

The algorithm's time complexity is O(m * n * 4900) and space complexity is O(4901).

## A solution in Python

```python
def minimizeTheDifference(mat, target):
    m, n = len(mat), len(mat[0])
    dp, new_dp = [1] + [0] * 4900, [0] * 4901
    for i in range(m):
        for j in range(n):
            for k in range(4900 - mat[i][j] + 1):
                new_dp[k + mat[i][j]] |= dp[k]
        dp, new_dp = new_dp, [0] * 4901
    for i in range(4901):
        if dp[i]:
            return abs(target - i)
    return float('inf')
```
The given problem is a variation of the subset sum problem. Instead of checking all combinations using backtracking, we can use dynamic programming to optimize it. We use an array `dp` of size 4901 to store whether a sum value is possible or not.

1. Initialize the `dp` array with 0, except `dp[0] = 1`, which means sum 0 is possible.
2. For each row in the matrix, we create a temporary `new_dp` array and loop through all columns.
3. For each column, iterate through the `dp` array, and if `dp[k] = 1`, set `new_dp[k + mat[i][j]] = 1`. It means the sum `k + mat[i][j]` is possible based on the current `dp`.
4. Swap `dp` and `new_dp` arrays for the next iteration.
5. After iterating through all rows, go through `dp`, if `dp[i] = 1`, return the absolute difference between i and the target.
6. If we didn't find a possible sum, return the maximum possible absolute difference.

The algorithm's time complexity is O(m * n * 4900) and space complexity is O(4901).

## A solution in Javascript

```javascript
function minimizeTheDifference(mat, target) {
    const m = mat.length, n = mat[0].length;
    let dp = new Uint8Array(4901), new_dp = new Uint8Array(4901);
    dp[0] = 1;
    for (let i = 0; i < m; ++i) {
        new_dp.fill(0);
        for (let j = 0; j < n; ++j) {
            for (let k = 0; k + mat[i][j] < 4901; ++k) {
                new_dp[k + mat[i][j]] |= dp[k];
            }
        }
        [dp, new_dp] = [new_dp, dp];
    }
    for (let i = 0; i < 4901; ++i) {
        if (dp[i]) return Math.abs(target - i);
    }
    return Infinity;
}
```
The given problem is a variation of the subset sum problem. Instead of checking all combinations using backtracking, we can use dynamic programming to optimize it. We use an array `dp` of size 4901 to store whether a sum value is possible or not.

1. Initialize the `dp` array with 0, except `dp[0] = 1`, which means sum 0 is possible.
2. For each row in the matrix, we create a temporary `new_dp` array and loop through all columns.
3. For each column, iterate through the `dp` array, and if `dp[k] = 1`, set `new_dp[k + mat[i][j]] = 1`. It means the sum `k + mat[i][j]` is possible based on the current `dp`.
4. Swap `dp` and `new_dp` arrays for the next iteration.
5. After iterating through all rows, go through `dp`, if `dp[i] = 1`, return the absolute difference between i and the target.
6. If we didn't find a possible sum, return the maximum possible absolute difference.

The algorithm's time complexity is O(m * n * 4900) and space complexity is O(4901).


# Adding Spaces to a String

- slug: adding-spaces-to-a-string
- difficulty: Medium

You are given a **0-indexed** string `s` and a **0-indexed** integer array `spaces` that describes the indices in the original string where spaces will be added. Each space should be inserted **before** the character at the given index.

*   For example, given `s = "EnjoyYourCoffee "` and `spaces = [5, 9]`, we place spaces before `'Y'` and `'C'`, which are at indices `5` and `9` respectively. Thus, we obtain `"Enjoy **Y**our **C**offee "`.

Return _the modified string **after** the spaces have been added._

**Example 1:**

**Input:** s =  "LeetcodeHelpsMeLearn ", spaces = \[8,13,15\]
**Output:**  "Leetcode Helps Me Learn "
**Explanation:**
The indices 8, 13, and 15 correspond to the underlined characters in  "Leetcode**H**elps**M**e**L**earn ".
We then place spaces before those characters.

**Example 2:**

**Input:** s =  "icodeinpython ", spaces = \[1,5,7,9\]
**Output:**  "i code in py thon "
**Explanation:**
The indices 1, 5, 7, and 9 correspond to the underlined characters in  "i**c**ode**i**n**p**y**t**hon ".
We then place spaces before those characters.

**Example 3:**

**Input:** s =  "spacing ", spaces = \[0,1,2,3,4,5,6\]
**Output:**  " s p a c i n g "
**Explanation:**
We are also able to place spaces before the first character of the string.

**Constraints:**

*   `1 <= s.length <= 3 * 105`
*   `s` consists only of lowercase and uppercase English letters.
*   `1 <= spaces.length <= 3 * 105`
*   `0 <= spaces[i] <= s.length - 1`
*   All the values of `spaces` are **strictly increasing**.

## A solution in Java

```java
import java.util.*;

class Solution {
    public int[] recoverArray(int n, int[] sums) {
        TreeMap<Integer, Integer> map = new TreeMap<>();
        for (int sum : sums) {
            map.put(sum, map.getOrDefault(sum, 0) + 1);
        }
        int[] ans = new int[n];
        for (int i = 0; i < n; ++i) {
            int num = map.firstKey();
            decrement(map, num);
            for (int prevNum : ans) {
                decrement(map, num - prevNum);
            }
            ans[i] = num;
        }
        return ans;
    }

    private void decrement(TreeMap<Integer, Integer> map, int key) {
        int count = map.get(key) - 1;
        if (count == 0) {
            map.remove(key);
        } else {
            map.put(key, count);
        }
    }
}
```
The algorithm first initializes a counter (multiset/map) from the input `sums` array. Then, it iterates `n` times, each time finding the highest remaining count key (sum) and removing it from the counter. It also removes the corresponding differences between this key (sum) and previously found keys (sums) from the counter. Finally, it adds the key (sum) to the result array `ans`. Since there will always be at least one correct answer, this algorithm ensures that the result array is one of the valid answers.

## A solution in C++

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

std::vector<int> recoverArray(int n, std::vector<int>& sums) {
    std::multiset<int> set(sums.begin(), sums.end());
    std::vector<int> ans(n);
    for (int i = 0; i < n; ++i) {
        int num = *next(set.begin());
        set.erase(set.begin());
        for (int prevNum : ans) {
            set.erase(set.find(num - prevNum));
        }
        ans[i] = num;
    }
    return ans;
}
```
The algorithm first initializes a counter (multiset/map) from the input `sums` array. Then, it iterates `n` times, each time finding the highest remaining count key (sum) and removing it from the counter. It also removes the corresponding differences between this key (sum) and previously found keys (sums) from the counter. Finally, it adds the key (sum) to the result array `ans`. Since there will always be at least one correct answer, this algorithm ensures that the result array is one of the valid answers.

## A solution in Python

```python
from collections import Counter
def recoverArray(n, sums):
    counter = Counter(sums)
    ans = []
    for _ in range(n):
        num, _ = counter.most_common(1)[0]
        counter -= Counter([num] + [prevNum - num for prevNum in ans])
        ans.append(num)
    return ans
```
The algorithm first initializes a counter (multiset/map) from the input `sums` array. Then, it iterates `n` times, each time finding the highest remaining count key (sum) and removing it from the counter. It also removes the corresponding differences between this key (sum) and previously found keys (sums) from the counter. Finally, it adds the key (sum) to the result array `ans`. Since there will always be at least one correct answer, this algorithm ensures that the result array is one of the valid answers.

## A solution in Javascript

```javascript
function recoverArray(n, sums) {
    const counter = new Map();
    for (const sum of sums) {
        counter.set(sum, (counter.get(sum) || 0) + 1);
    }
    const ans = [];
    for (let i = 0; i < n; ++i) {
        const [num, count] = [...counter.entries()].sort((a, b) => b[1] - a[1])[0];
        counter.set(num, count - 1);
        for (const prevNum of ans) {
            const prevCount = counter.get(num - prevNum);
            if (prevCount === 1) {
                counter.delete(num - prevNum);
            } else {
                counter.set(num - prevNum, count - 1);
            }
        }
        ans.push(num);
    }
    return ans;
}
```
The algorithm first initializes a counter (multiset/map) from the input `sums` array. Then, it iterates `n` times, each time finding the highest remaining count key (sum) and removing it from the counter. It also removes the corresponding differences between this key (sum) and previously found keys (sums) from the counter. Finally, it adds the key (sum) to the result array `ans`. Since there will always be at least one correct answer, this algorithm ensures that the result array is one of the valid answers.


# Number of Smooth Descent Periods of a Stock

- slug: number-of-smooth-descent-periods-of-a-stock
- difficulty: Medium

You are given an integer array `prices` representing the daily price history of a stock, where `prices[i]` is the stock price on the `ith` day.

A **smooth descent period** of a stock consists of **one or more contiguous** days such that the price on each day is **lower** than the price on the **preceding day** by **exactly** `1`. The first day of the period is exempted from this rule.

Return _the number of **smooth descent periods**_.

**Example 1:**

**Input:** prices = \[3,2,1,4\]
**Output:** 7
**Explanation:** There are 7 smooth descent periods:
\[3\], \[2\], \[1\], \[4\], \[3,2\], \[2,1\], and \[3,2,1\]
Note that a period with one day is a smooth descent period by the definition.

**Example 2:**

**Input:** prices = \[8,6,7,7\]
**Output:** 4
**Explanation:** There are 4 smooth descent periods: \[8\], \[6\], \[7\], and \[7\]
Note that \[8,6\] is not a smooth descent period as 8 - 6 ≠ 1.

**Example 3:**

**Input:** prices = \[1\]
**Output:** 1
**Explanation:** There is 1 smooth descent period: \[1\]

**Constraints:**

*   `1 <= prices.length <= 105`
*   `1 <= prices[i] <= 105`

## A solution in Java

```java
public int numSmoothDescentPeriods(int[] prices) {
    int result = 0;
    int count = 0;
    for (int i = 1; i < prices.length; ++i) {
        if (prices[i] == prices[i - 1] - 1) {
            ++count;
        } else {
            count = 0;
        }
        result += count + 1;
    }
    return result + 1;
}
```
This algorithm iterates through the `prices` array, starting at index 1. At each index `i`, it checks if the current price is equal to the previous price minus 1. If this condition is true, it means that the two prices form a smooth descent pair and `count` is incremented. If the condition is not met, it means that the path is broken, so `count` is reset to 0. The result is incremented by `count + 1` at each step, and finally incremented by 1 at the end to account for the first day in the period. The time complexity is O(n), where n is the length of the prices array.

## A solution in C++

```cpp
int numSmoothDescentPeriods(vector<int>& prices) {
    int result = 0;
    int count = 0;
    for (int i = 1; i < prices.size(); ++i) {
        if (prices[i] == prices[i - 1] - 1) {
            ++count;
        } else {
            count = 0;
        }
        result += count + 1;
    }
    return result + 1;
}
```
This algorithm iterates through the `prices` array, starting at index 1. At each index `i`, it checks if the current price is equal to the previous price minus 1. If this condition is true, it means that the two prices form a smooth descent pair and `count` is incremented. If the condition is not met, it means that the path is broken, so `count` is reset to 0. The result is incremented by `count + 1` at each step, and finally incremented by 1 at the end to account for the first day in the period. The time complexity is O(n), where n is the length of the prices array.

## A solution in Python

```python
def num_smooth_descent_periods(prices):
    result = 0
    count = 0
    for i in range(1, len(prices)):
        if prices[i] == prices[i - 1] - 1:
            count += 1
        else:
            count = 0
        result += count + 1
    return result + 1
```
This algorithm iterates through the `prices` array, starting at index 1. At each index `i`, it checks if the current price is equal to the previous price minus 1. If this condition is true, it means that the two prices form a smooth descent pair and `count` is incremented. If the condition is not met, it means that the path is broken, so `count` is reset to 0. The result is incremented by `count + 1` at each step, and finally incremented by 1 at the end to account for the first day in the period. The time complexity is O(n), where n is the length of the prices array.

## A solution in Javascript

```javascript
function numSmoothDescentPeriods(prices) {
    let result = 0;
    let count = 0;
    for (let i = 1; i < prices.length; ++i) {
        if (prices[i] === prices[i - 1] - 1) {
            ++count;
        } else {
            count = 0;
        }
        result += count + 1;
    }
    return result + 1;
}
```
This algorithm iterates through the `prices` array, starting at index 1. At each index `i`, it checks if the current price is equal to the previous price minus 1. If this condition is true, it means that the two prices form a smooth descent pair and `count` is incremented. If the condition is not met, it means that the path is broken, so `count` is reset to 0. The result is incremented by `count + 1` at each step, and finally incremented by 1 at the end to account for the first day in the period. The time complexity is O(n), where n is the length of the prices array.


# Minimum Operations to Make the Array K-Increasing

- slug: minimum-operations-to-make-the-array-k-increasing
- difficulty: Hard

You are given a **0-indexed** array `arr` consisting of `n` positive integers, and a positive integer `k`.

The array `arr` is called **K-increasing** if `arr[i-k] <= arr[i]` holds for every index `i`, where `k <= i <= n-1`.

*   For example, `arr = [4, 1, 5, 2, 6, 2]` is K-increasing for `k = 2` because:
    *   `arr[0] <= arr[2] (4 <= 5)`
    *   `arr[1] <= arr[3] (1 <= 2)`
    *   `arr[2] <= arr[4] (5 <= 6)`
    *   `arr[3] <= arr[5] (2 <= 2)`
*   However, the same `arr` is not K-increasing for `k = 1` (because `arr[0] > arr[1]`) or `k = 3` (because `arr[0] > arr[3]`).

In one **operation**, you can choose an index `i` and **change** `arr[i]` into **any** positive integer.

Return _the **minimum number of operations** required to make the array K-increasing for the given_ `k`.

**Example 1:**

**Input:** arr = \[5,4,3,2,1\], k = 1
**Output:** 4
**Explanation:**
For k = 1, the resultant array has to be non-decreasing.
Some of the K-increasing arrays that can be formed are \[5,**6**,**7**,**8**,**9**\], \[**1**,**1**,**1**,**1**,1\], \[**2**,**2**,3,**4**,**4**\]. All of them require 4 operations.
It is suboptimal to change the array to, for example, \[**6**,**7**,**8**,**9**,**10**\] because it would take 5 operations.
It can be shown that we cannot make the array K-increasing in less than 4 operations.

**Example 2:**

**Input:** arr = \[4,1,5,2,6,2\], k = 2
**Output:** 0
**Explanation:**
This is the same example as the one in the problem description.
Here, for every index i where 2 <= i <= 5, arr\[i-2\] <= arr\[i\].
Since the given array is already K-increasing, we do not need to perform any operations.

**Example 3:**

**Input:** arr = \[4,1,5,2,6,2\], k = 3
**Output:** 2
**Explanation:**
Indices 3 and 5 are the only ones not satisfying arr\[i-3\] <= arr\[i\] for 3 <= i <= 5.
One of the ways we can make the array K-increasing is by changing arr\[3\] to 4 and arr\[5\] to 5.
The array will now be \[4,1,5,**4**,6,**5**\].
Note that there can be other ways to make the array K-increasing, but none of them require less than 2 operations.

**Constraints:**

*   `1 <= arr.length <= 105`
*   `1 <= arr[i], k <= arr.length`

## A solution in Java

```java
public int minOperations(int[] arr, int k) {
    int[] dp = new int[arr.length];
    for (int i = k; i < arr.length; i++) {
        dp[i] = Math.max(dp[i - k] + 1 - (arr[i] - arr[i - k]), 0);
    }
    return Arrays.stream(dp).sum();
}
```
First, initialize an array called `dp` with the same length as `arr`. This array will store the minimum number of operations needed for every element `arr[i]` to satisfy the K-increasing requirement.

Iterate from `k` to `n-1` (inclusive) through the array. In each step, update the `dp[i]` with the minimum number of operations needed to change `arr[i]` to be K-increasing. Calculate this as the maximum between (`dp[i - k]` plus `1`, minus the difference between `arr[i]` and `arr[i - k]`) and `0`. Using the maximum function ensures that we don't end up with negative values for the number of operations.

Finally, return the sum of all the values in the `dp` array. This will provide the minimum number of operations required to make the entire array K-increasing.

## A solution in C++

```cpp
int minOperations(vector<int>& arr, int k) {
    vector<int> dp(arr.size(), 0);
    for (int i = k; i < arr.size(); i++) {
        dp[i] = max(dp[i - k] + 1 - (arr[i] - arr[i - k]), 0);
    }
    return accumulate(dp.begin(), dp.end(), 0);
}
```
First, initialize an array called `dp` with the same length as `arr`. This array will store the minimum number of operations needed for every element `arr[i]` to satisfy the K-increasing requirement.

Iterate from `k` to `n-1` (inclusive) through the array. In each step, update the `dp[i]` with the minimum number of operations needed to change `arr[i]` to be K-increasing. Calculate this as the maximum between (`dp[i - k]` plus `1`, minus the difference between `arr[i]` and `arr[i - k]`) and `0`. Using the maximum function ensures that we don't end up with negative values for the number of operations.

Finally, return the sum of all the values in the `dp` array. This will provide the minimum number of operations required to make the entire array K-increasing.

## A solution in Python

```python
def minOperations(arr, k):
    dp = [0] * len(arr)
    for i in range(k, len(arr)):
        dp[i] = max(dp[i - k] + 1 - (arr[i] - arr[i - k]), 0)
    return sum(dp)
```
First, initialize an array called `dp` with the same length as `arr`. This array will store the minimum number of operations needed for every element `arr[i]` to satisfy the K-increasing requirement.

Iterate from `k` to `n-1` (inclusive) through the array. In each step, update the `dp[i]` with the minimum number of operations needed to change `arr[i]` to be K-increasing. Calculate this as the maximum between (`dp[i - k]` plus `1`, minus the difference between `arr[i]` and `arr[i - k]`) and `0`. Using the maximum function ensures that we don't end up with negative values for the number of operations.

Finally, return the sum of all the values in the `dp` array. This will provide the minimum number of operations required to make the entire array K-increasing.

## A solution in Javascript

```javascript
function minOperations(arr, k) {
    const dp = new Array(arr.length).fill(0);
    for (let i = k; i < arr.length; i++) {
        dp[i] = Math.max(dp[i - k] + 1 - (arr[i] - arr[i - k]), 0);
    }
    return dp.reduce((a, b) => a + b, 0);
}
```
First, initialize an array called `dp` with the same length as `arr`. This array will store the minimum number of operations needed for every element `arr[i]` to satisfy the K-increasing requirement.

Iterate from `k` to `n-1` (inclusive) through the array. In each step, update the `dp[i]` with the minimum number of operations needed to change `arr[i]` to be K-increasing. Calculate this as the maximum between (`dp[i - k]` plus `1`, minus the difference between `arr[i]` and `arr[i - k]`) and `0`. Using the maximum function ensures that we don't end up with negative values for the number of operations.

Finally, return the sum of all the values in the `dp` array. This will provide the minimum number of operations required to make the entire array K-increasing.


# Elements in Array After Removing and Replacing Elements

- slug: elements-in-array-after-removing-and-replacing-elements
- difficulty: Medium

You are given a **0-indexed** integer array `nums`. Initially on minute `0`, the array is unchanged. Every minute, the **leftmost** element in `nums` is removed until no elements remain. Then, every minute, one element is appended to the **end** of `nums`, in the order they were removed in, until the original array is restored. This process repeats indefinitely.

*   For example, the array `[0,1,2]` would change as follows: `[0,1,2] -> [1,2] -> [2] -> [] -> [0] -> [0,1] -> [0,1,2] -> [1,2] -> [2] -> [] -> [0] -> [0,1] -> [0,1,2] -> ...`

You are also given a 2D integer array `queries` of size `n` where `queries[j] = [timej, indexj]`. The answer to the `jth` query is:

*   `nums[indexj]` if `indexj < nums.length` at minute `timej`
*   `-1` if `indexj >= nums.length` at minute `timej`

Return _an integer array `ans` of size_ `n` _where_ `ans[j]` _is the answer to the_ `jth` _query_.

**Example 1:**

**Input:** nums = \[0,1,2\], queries = \[\[0,2\],\[2,0\],\[3,2\],\[5,0\]\]
**Output:** \[2,2,-1,0\]
**Explanation:**
Minute 0: \[0,1,2\] - All elements are in the nums.
Minute 1: \[1,2\]   - The leftmost element, 0, is removed.
Minute 2: \[2\]     - The leftmost element, 1, is removed.
Minute 3: \[\]      - The leftmost element, 2, is removed.
Minute 4: \[0\]     - 0 is added to the end of nums.
Minute 5: \[0,1\]   - 1 is added to the end of nums.

At minute 0, nums\[2\] is 2.
At minute 2, nums\[0\] is 2.
At minute 3, nums\[2\] does not exist.
At minute 5, nums\[0\] is 0.

**Example 2:**

**Input:** nums = \[2\], queries = \[\[0,0\],\[1,0\],\[2,0\],\[3,0\]\]
**Output:** \[2,-1,2,-1\]
Minute 0: \[2\] - All elements are in the nums.
Minute 1: \[\]  - The leftmost element, 2, is removed.
Minute 2: \[2\] - 2 is added to the end of nums.
Minute 3: \[\]  - The leftmost element, 2, is removed.

At minute 0, nums\[0\] is 2.
At minute 1, nums\[0\] does not exist.
At minute 2, nums\[0\] is 2.
At minute 3, nums\[0\] does not exist.

**Constraints:**

*   `1 <= nums.length <= 100`
*   `0 <= nums[i] <= 100`
*   `n == queries.length`
*   `1 <= n <= 105`
*   `queries[j].length == 2`
*   `0 <= timej <= 105`
*   `0 <= indexj < nums.length`

## A solution in Java

```java
import java.util.Arrays;
import java.util.Comparator;

public String kthLargestNumber(String[] nums, int k) {
    Arrays.sort(nums, (a, b) -> {
        if (a.length() == b.length()) return a.compareTo(b);
        return a.length() - b.length();
    });
    return nums[nums.length - k];
}
```
1. Sort the given nums array of strings based on their lengths (i.e., based on the number of digits). If the lengths are equal, sort the strings lexicographically.
2. Return the element at index (length - k), as it represents the kth largest number in the sorted array.

## A solution in C++

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

std::string kthLargestNumber(std::vector<std::string> &nums, int k) {
    std::sort(nums.begin(), nums.end(), [](const std::string &a, const std::string &b) {
        if (a.size() == b.size()) return a < b;
        return a.size() < b.size();
    });
    return nums[nums.size() - k];
}
```
1. Sort the given nums array of strings based on their lengths (i.e., based on the number of digits). If the lengths are equal, sort the strings lexicographically.
2. Return the element at index (length - k), as it represents the kth largest number in the sorted array.

## A solution in Python

```python
def kthLargestNumber(nums, k):
    nums.sort(key=lambda x: (len(x), x))
    return nums[-k]
```
1. Sort the given nums array of strings based on their lengths (i.e., based on the number of digits). If the lengths are equal, sort the strings lexicographically.
2. Return the element at index (length - k), as it represents the kth largest number in the sorted array.

## A solution in Javascript

```javascript
function kthLargestNumber(nums, k) {
    nums.sort((a, b) => {
        if (a.length == b.length) return a.localeCompare(b);
        return a.length - b.length;
    });
    return nums[nums.length - k];
}
```
1. Sort the given nums array of strings based on their lengths (i.e., based on the number of digits). If the lengths are equal, sort the strings lexicographically.
2. Return the element at index (length - k), as it represents the kth largest number in the sorted array.


# Maximum Number of Words Found in Sentences

- slug: maximum-number-of-words-found-in-sentences
- difficulty: Easy

A **sentence** is a list of **words** that are separated by a single space with no leading or trailing spaces.

You are given an array of strings `sentences`, where each `sentences[i]` represents a single **sentence**.

Return _the **maximum number of words** that appear in a single sentence_.

**Example 1:**

**Input:** sentences = \[ "alice and bob love leetcode ",  "i think so too ",  "this is great thanks very much "\]
**Output:** 6
**Explanation:**
- The first sentence,  "alice and bob love leetcode ", has 5 words in total.
- The second sentence,  "i think so too ", has 4 words in total.
- The third sentence,  "this is great thanks very much ", has 6 words in total.
Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words.

**Example 2:**

**Input:** sentences = \[ "please wait ",  "continue to fight ",  "continue to win "\]
**Output:** 3
**Explanation:** It is possible that multiple sentences contain the same number of words.
In this example, the second and third sentences (underlined) have the same number of words.

**Constraints:**

*   `1 <= sentences.length <= 100`
*   `1 <= sentences[i].length <= 100`
*   `sentences[i]` consists only of lowercase English letters and `' '` only.
*   `sentences[i]` does not have leading or trailing spaces.
*   All the words in `sentences[i]` are separated by a single space.

## A solution in Java

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

public int minSessions(int[] tasks, int sessionTime) {
    List<Integer> sessions = new ArrayList<>();
    List<Integer> taskList = new ArrayList<>();
    for (int task : tasks) taskList.add(task);
    Collections.sort(taskList, Collections.reverseOrder());

    for (int task : taskList) {
        boolean added = false;
        for (int i = 0; i < sessions.size(); i++) {
            if (sessions.get(i) + task <= sessionTime) {
                sessions.set(i, sessions.get(i) + task);
                added = true;
                break;
            }
        }

        if (!added) {
            sessions.add(task);
        }
    }

    return sessions.size();
}
```
The algorithm starts by sorting the tasks array in descending order. Then, for each task in tasks, it iterates over the sessions array and tries to insert the task into the first session that has sufficient remaining time. If no session can accommodate the task, a new session is created.

In the end, the size of the sessions array is the answer, which represents the minimum number of work sessions required to finish all tasks.

## A solution in C++

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

int minSessions(std::vector<int>& tasks, int sessionTime) {
    std::sort(tasks.begin(), tasks.end(), std::greater<int>());
    std::vector<int> sessions;

    for (int task : tasks) {
        bool added = false;
        for (int& session : sessions) {
            if (session + task <= sessionTime) {
                session += task;
                added = true;
                break;
            }
        }

        if (!added) {
            sessions.push_back(task);
        }
    }

    return sessions.size();
}
```
The algorithm starts by sorting the tasks array in descending order. Then, for each task in tasks, it iterates over the sessions array and tries to insert the task into the first session that has sufficient remaining time. If no session can accommodate the task, a new session is created.

In the end, the size of the sessions array is the answer, which represents the minimum number of work sessions required to finish all tasks.

## A solution in Python

```python
def min_sessions(tasks, session_time):
    sessions = []
    tasks.sort(reverse=True)

    for task in tasks:
        added = False
        for session_idx, session in enumerate(sessions):
            if session + task <= session_time:
                sessions[session_idx] += task
                added = True
                break

        if not added:
            sessions.append(task)

    return len(sessions)
```
The algorithm starts by sorting the tasks array in descending order. Then, for each task in tasks, it iterates over the sessions array and tries to insert the task into the first session that has sufficient remaining time. If no session can accommodate the task, a new session is created.

In the end, the size of the sessions array is the answer, which represents the minimum number of work sessions required to finish all tasks.

## A solution in Javascript

```javascript
function minSessions(tasks, sessionTime) {
    const sessions = [];
    tasks.sort((a, b) => b - a);

    for (let task of tasks) {
        let added = false;

        for (let i = 0; i < sessions.length; i++) {
            if (sessions[i] + task <= sessionTime) {
                sessions[i] += task;
                added = true;
                break;
            }
        }

        if (!added) {
            sessions.push(task);
        }
    }

    return sessions.length;
}
```
The algorithm starts by sorting the tasks array in descending order. Then, for each task in tasks, it iterates over the sessions array and tries to insert the task into the first session that has sufficient remaining time. If no session can accommodate the task, a new session is created.

In the end, the size of the sessions array is the answer, which represents the minimum number of work sessions required to finish all tasks.