id
int64
1
3.65k
title
stringlengths
3
79
difficulty
stringclasses
3 values
description
stringlengths
430
25.4k
tags
stringlengths
0
131
language
stringclasses
19 values
solution
stringlengths
47
20.6k
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
C++
class Solution { public: long long maxSubarrays(int n, vector<vector<int>>& conflictingPairs) { vector<vector<int>> g(n + 1); for (auto& pair : conflictingPairs) { int a = pair[0], b = pair[1]; if (a > b) { swap(a, b); } g[a].push_back(b); } vector<long long> cnt(n + 2, 0); long long ans = 0, add = 0; int b1 = n + 1, b2 = n + 1; for (int a = n; a > 0; --a) { for (int b : g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = max(add, cnt[b1]); } ans += add; return ans; } };
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Go
func maxSubarrays(n int, conflictingPairs [][]int) (ans int64) { g := make([][]int, n+1) for _, pair := range conflictingPairs { a, b := pair[0], pair[1] if a > b { a, b = b, a } g[a] = append(g[a], b) } cnt := make([]int64, n+2) var add int64 b1, b2 := n+1, n+1 for a := n; a > 0; a-- { for _, b := range g[a] { if b < b1 { b2 = b1 b1 = b } else if b < b2 { b2 = b } } ans += int64(b1 - a) cnt[b1] += int64(b2 - b1) if cnt[b1] > add { add = cnt[b1] } } ans += add return ans }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Java
class Solution { public long maxSubarrays(int n, int[][] conflictingPairs) { List<Integer>[] g = new List[n + 1]; Arrays.setAll(g, k -> new ArrayList<>()); for (int[] pair : conflictingPairs) { int a = pair[0], b = pair[1]; if (a > b) { int c = a; a = b; b = c; } g[a].add(b); } long[] cnt = new long[n + 2]; long ans = 0, add = 0; int b1 = n + 1, b2 = n + 1; for (int a = n; a > 0; --a) { for (int b : g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = Math.max(add, cnt[b1]); } ans += add; return ans; } }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Python
class Solution: def maxSubarrays(self, n: int, conflictingPairs: List[List[int]]) -> int: g = [[] for _ in range(n + 1)] for a, b in conflictingPairs: if a > b: a, b = b, a g[a].append(b) cnt = [0] * (n + 2) ans = add = 0 b1 = b2 = n + 1 for a in range(n, 0, -1): for b in g[a]: if b < b1: b2, b1 = b1, b elif b < b2: b2 = b ans += b1 - a cnt[b1] += b2 - b1 add = max(add, cnt[b1]) ans += add return ans
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
Rust
impl Solution { pub fn max_subarrays(n: i32, conflicting_pairs: Vec<Vec<i32>>) -> i64 { let mut g: Vec<Vec<i32>> = vec![vec![]; (n + 1) as usize]; for pair in conflicting_pairs { let mut a = pair[0]; let mut b = pair[1]; if a > b { std::mem::swap(&mut a, &mut b); } g[a as usize].push(b); } let mut cnt: Vec<i64> = vec![0; (n + 2) as usize]; let mut ans = 0i64; let mut add = 0i64; let mut b1 = n + 1; let mut b2 = n + 1; for a in (1..=n).rev() { for &b in &g[a as usize] { if b < b1 { b2 = b1; b1 = b; } else if b < b2 { b2 = b; } } ans += (b1 - a) as i64; cnt[b1 as usize] += (b2 - b1) as i64; add = std::cmp::max(add, cnt[b1 as usize]); } ans += add; ans } }
3,480
Maximize Subarrays After Removing One Conflicting Pair
Hard
<p>You are given an integer <code>n</code> which represents an array <code>nums</code> containing the numbers from 1 to <code>n</code> in order. Additionally, you are given a 2D array <code>conflictingPairs</code>, where <code>conflictingPairs[i] = [a, b]</code> indicates that <code>a</code> and <code>b</code> form a conflicting pair.</p> <p>Remove <strong>exactly</strong> one element from <code>conflictingPairs</code>. Afterward, count the number of <span data-keyword="subarray-nonempty">non-empty subarrays</span> of <code>nums</code> which do not contain both <code>a</code> and <code>b</code> for any remaining conflicting pair <code>[a, b]</code>.</p> <p>Return the <strong>maximum</strong> number of subarrays possible after removing <strong>exactly</strong> one conflicting pair.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 4, conflictingPairs = [[2,3],[1,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">9</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[2, 3]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[1, 4]]</code>.</li> <li>There are 9 subarrays in <code>nums</code> where <code>[1, 4]</code> do not appear together. They are <code>[1]</code>, <code>[2]</code>, <code>[3]</code>, <code>[4]</code>, <code>[1, 2]</code>, <code>[2, 3]</code>, <code>[3, 4]</code>, <code>[1, 2, 3]</code> and <code>[2, 3, 4]</code>.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 9.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Remove <code>[1, 2]</code> from <code>conflictingPairs</code>. Now, <code>conflictingPairs = [[2, 5], [3, 5]]</code>.</li> <li>There are 12 subarrays in <code>nums</code> where <code>[2, 5]</code> and <code>[3, 5]</code> do not appear together.</li> <li>The maximum number of subarrays we can achieve after removing one element from <code>conflictingPairs</code> is 12.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= conflictingPairs.length &lt;= 2 * n</code></li> <li><code>conflictingPairs[i].length == 2</code></li> <li><code>1 &lt;= conflictingPairs[i][j] &lt;= n</code></li> <li><code>conflictingPairs[i][0] != conflictingPairs[i][1]</code></li> </ul>
Segment Tree; Array; Enumeration; Prefix Sum
TypeScript
function maxSubarrays(n: number, conflictingPairs: number[][]): number { const g: number[][] = Array.from({ length: n + 1 }, () => []); for (let [a, b] of conflictingPairs) { if (a > b) { [a, b] = [b, a]; } g[a].push(b); } const cnt: number[] = Array(n + 2).fill(0); let ans = 0, add = 0; let b1 = n + 1, b2 = n + 1; for (let a = n; a > 0; a--) { for (const b of g[a]) { if (b < b1) { b2 = b1; b1 = b; } else if (b < b2) { b2 = b; } } ans += b1 - a; cnt[b1] += b2 - b1; add = Math.max(add, cnt[b1]); } ans += add; return ans; }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
C++
class Solution { public: string applySubstitutions(vector<vector<string>>& replacements, string text) { unordered_map<string, string> d; for (const auto& e : replacements) { d[e[0]] = e[1]; } auto dfs = [&](this auto&& dfs, const string& s) -> string { size_t i = s.find('%'); if (i == string::npos) { return s; } size_t j = s.find('%', i + 1); if (j == string::npos) { return s; } string key = s.substr(i + 1, j - i - 1); string replacement = dfs(d[key]); return s.substr(0, i) + replacement + dfs(s.substr(j + 1)); }; return dfs(text); } };
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Go
func applySubstitutions(replacements [][]string, text string) string { d := make(map[string]string) for _, e := range replacements { d[e[0]] = e[1] } var dfs func(string) string dfs = func(s string) string { i := strings.Index(s, "%") if i == -1 { return s } j := strings.Index(s[i+1:], "%") if j == -1 { return s } j += i + 1 key := s[i+1 : j] replacement := dfs(d[key]) return s[:i] + replacement + dfs(s[j+1:]) } return dfs(text) }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Java
class Solution { private final Map<String, String> d = new HashMap<>(); public String applySubstitutions(List<List<String>> replacements, String text) { for (List<String> e : replacements) { d.put(e.get(0), e.get(1)); } return dfs(text); } private String dfs(String s) { int i = s.indexOf("%"); if (i == -1) { return s; } int j = s.indexOf("%", i + 1); if (j == -1) { return s; } String key = s.substring(i + 1, j); String replacement = dfs(d.getOrDefault(key, "")); return s.substring(0, i) + replacement + dfs(s.substring(j + 1)); } }
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
Python
class Solution: def applySubstitutions(self, replacements: List[List[str]], text: str) -> str: def dfs(s: str) -> str: i = s.find("%") if i == -1: return s j = s.find("%", i + 1) if j == -1: return s key = s[i + 1 : j] replacement = dfs(d[key]) return s[:i] + replacement + dfs(s[j + 1 :]) d = {s: t for s, t in replacements} return dfs(text)
3,481
Apply Substitutions
Medium
<p data-end="384" data-start="34">You are given a <code>replacements</code> mapping and a <code>text</code> string that may contain <strong>placeholders</strong> formatted as <code data-end="139" data-start="132">%var%</code>, where each <code>var</code> corresponds to a key in the <code>replacements</code> mapping. Each replacement value may itself contain <strong>one or more</strong> such <strong>placeholders</strong>. Each <strong>placeholder</strong> is replaced by the value associated with its corresponding replacement key.</p> <p data-end="353" data-start="34">Return the fully substituted <code>text</code> string which <strong>does not</strong> contain any <strong>placeholders</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;abc&quot;],[&quot;B&quot;,&quot;def&quot;]], text = &quot;%A%_%B%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;abc_def&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="238" data-start="71"> <li data-end="138" data-start="71">The mapping associates <code data-end="101" data-start="96">&quot;A&quot;</code> with <code data-end="114" data-start="107">&quot;abc&quot;</code> and <code data-end="124" data-start="119">&quot;B&quot;</code> with <code data-end="137" data-start="130">&quot;def&quot;</code>.</li> <li data-end="203" data-start="139">Replace <code data-end="154" data-start="149">%A%</code> with <code data-end="167" data-start="160">&quot;abc&quot;</code> and <code data-end="177" data-start="172">%B%</code> with <code data-end="190" data-start="183">&quot;def&quot;</code> in the text.</li> <li data-end="238" data-start="204">The final text becomes <code data-end="237" data-start="226">&quot;abc_def&quot;</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">replacements = [[&quot;A&quot;,&quot;bce&quot;],[&quot;B&quot;,&quot;ace&quot;],[&quot;C&quot;,&quot;abc%B%&quot;]], text = &quot;%A%_%B%_%C%&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bce_ace_abcace&quot;</span></p> <p><strong>Explanation:</strong></p> <ul data-end="541" data-is-last-node="" data-is-only-node="" data-start="255"> <li data-end="346" data-start="255">The mapping associates <code data-end="285" data-start="280">&quot;A&quot;</code> with <code data-end="298" data-start="291">&quot;bce&quot;</code>, <code data-end="305" data-start="300">&quot;B&quot;</code> with <code data-end="318" data-start="311">&quot;ace&quot;</code>, and <code data-end="329" data-start="324">&quot;C&quot;</code> with <code data-end="345" data-start="335">&quot;abc%B%&quot;</code>.</li> <li data-end="411" data-start="347">Replace <code data-end="362" data-start="357">%A%</code> with <code data-end="375" data-start="368">&quot;bce&quot;</code> and <code data-end="385" data-start="380">%B%</code> with <code data-end="398" data-start="391">&quot;ace&quot;</code> in the text.</li> <li data-end="496" data-start="412">Then, for <code data-end="429" data-start="424">%C%</code>, substitute <code data-end="447" data-start="442">%B%</code> in <code data-end="461" data-start="451">&quot;abc%B%&quot;</code> with <code data-end="474" data-start="467">&quot;ace&quot;</code> to obtain <code data-end="495" data-start="485">&quot;abcace&quot;</code>.</li> <li data-end="541" data-is-last-node="" data-start="497">The final text becomes <code data-end="540" data-start="522">&quot;bce_ace_abcace&quot;</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li data-end="1432" data-start="1398"><code>1 &lt;= replacements.length &lt;= 10</code></li> <li data-end="1683" data-start="1433">Each element of <code data-end="1465" data-start="1451">replacements</code> is a two-element list <code data-end="1502" data-start="1488">[key, value]</code>, where: <ul data-end="1683" data-start="1513"> <li data-end="1558" data-start="1513"><code data-end="1520" data-start="1515">key</code> is a single uppercase English letter.</li> <li data-end="1683" data-start="1561"><code data-end="1570" data-start="1563">value</code> is a non-empty string of at most 8 characters that may contain zero or more placeholders formatted as <code data-end="1682" data-start="1673">%&lt;key&gt;%</code>.</li> </ul> </li> <li data-end="726" data-start="688">All replacement keys are unique.</li> <li data-end="1875" data-start="1723">The <code>text</code> string is formed by concatenating all key placeholders (formatted as <code data-end="1808" data-start="1799">%&lt;key&gt;%</code>) randomly from the replacements mapping, separated by underscores.</li> <li data-end="1942" data-start="1876"><code>text.length == 4 * replacements.length - 1</code></li> <li data-end="2052" data-start="1943">Every placeholder in the <code>text</code> or in any replacement value corresponds to a key in the <code>replacements</code> mapping.</li> <li data-end="2265" data-start="2205">There are no cyclic dependencies between replacement keys.</li> </ul>
Depth-First Search; Breadth-First Search; Graph; Topological Sort; Array; Hash Table; String
TypeScript
function applySubstitutions(replacements: string[][], text: string): string { const d: Record<string, string> = {}; for (const [key, value] of replacements) { d[key] = value; } const dfs = (s: string): string => { const i = s.indexOf('%'); if (i === -1) { return s; } const j = s.indexOf('%', i + 1); if (j === -1) { return s; } const key = s.slice(i + 1, j); const replacement = dfs(d[key] ?? ''); return s.slice(0, i) + replacement + dfs(s.slice(j + 1)); }; return dfs(text); }
3,482
Analyze Organization Hierarchy
Hard
<p>Table: <code>Employees</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | employee_id | int | | employee_name | varchar | | manager_id | int | | salary | int | | department | varchar | +----------------+----------+ employee_id is the unique key for this table. Each row contains information about an employee, including their ID, name, their manager&#39;s ID, salary, and department. manager_id is null for the top-level manager (CEO). </pre> <p>Write a solution to analyze the organizational hierarchy and answer the following:</p> <ol> <li><strong>Hierarchy Levels:</strong> For each employee, determine their level in the organization (CEO is level <code>1</code>, employees reporting directly to the CEO are level <code>2</code>, and so on).</li> <li><strong>Team Size:</strong> For each employee who is a manager, count the total number of employees under them (direct and indirect reports).</li> <li><strong>Salary Budget:</strong> For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).</li> </ol> <p>Return <em>the result table ordered by&nbsp;<em>the result ordered by <strong>level</strong> in <strong>ascending</strong> order, then by <strong>budget</strong> in <strong>descending</strong> order, and finally by <strong>employee_name</strong> in <strong>ascending</strong> order</em>.</em></p> <p><em>The result format is in the following example.</em></p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Employees table:</p> <pre class="example-io"> +-------------+---------------+------------+--------+-------------+ | employee_id | employee_name | manager_id | salary | department | +-------------+---------------+------------+--------+-------------+ | 1 | Alice | null | 12000 | Executive | | 2 | Bob | 1 | 10000 | Sales | | 3 | Charlie | 1 | 10000 | Engineering | | 4 | David | 2 | 7500 | Sales | | 5 | Eva | 2 | 7500 | Sales | | 6 | Frank | 3 | 9000 | Engineering | | 7 | Grace | 3 | 8500 | Engineering | | 8 | Hank | 4 | 6000 | Sales | | 9 | Ivy | 6 | 7000 | Engineering | | 10 | Judy | 6 | 7000 | Engineering | +-------------+---------------+------------+--------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------+-------+-----------+--------+ | employee_id | employee_name | level | team_size | budget | +-------------+---------------+-------+-----------+--------+ | 1 | Alice | 1 | 9 | 84500 | | 3 | Charlie | 2 | 4 | 41500 | | 2 | Bob | 2 | 3 | 31000 | | 6 | Frank | 3 | 2 | 23000 | | 4 | David | 3 | 1 | 13500 | | 7 | Grace | 3 | 0 | 8500 | | 5 | Eva | 3 | 0 | 7500 | | 9 | Ivy | 4 | 0 | 7000 | | 10 | Judy | 4 | 0 | 7000 | | 8 | Hank | 4 | 0 | 6000 | +-------------+---------------+-------+-----------+--------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Organization Structure:</strong> <ul> <li>Alice (ID: 1) is the CEO (level 1) with no manager</li> <li>Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)</li> <li>David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)</li> <li>Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)</li> </ul> </li> <li><strong>Level Calculation:</strong> <ul> <li>The CEO (Alice) is at level 1</li> <li>Each subsequent level of management adds 1 to the level</li> </ul> </li> <li><strong>Team Size Calculation:</strong> <ul> <li>Alice has 9 employees under her (the entire company except herself)</li> <li>Bob has 3 employees (David, Eva, and Hank)</li> <li>Charlie has 4 employees (Frank, Grace, Ivy, and Judy)</li> <li>David has 1 employee (Hank)</li> <li>Frank has 2 employees (Ivy and Judy)</li> <li>Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)</li> </ul> </li> <li><strong>Budget Calculation:</strong> <ul> <li>Alice&#39;s budget: Her salary (12000) + all employees&#39; salaries (72500) = 84500</li> <li>Charlie&#39;s budget: His salary (10000) + Frank&#39;s budget (23000) + Grace&#39;s salary (8500) = 41500</li> <li>Bob&#39;s budget: His salary (10000) + David&#39;s budget (13500) + Eva&#39;s salary (7500) = 31000</li> <li>Frank&#39;s budget: His salary (9000) + Ivy&#39;s salary (7000) + Judy&#39;s salary (7000) = 23000</li> <li>David&#39;s budget: His salary (7500) + Hank&#39;s salary (6000) = 13500</li> <li>Employees with no direct reports have budgets equal to their own salary</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered first by level in ascending order</li> <li>Within the same level, employees are ordered by budget in descending order then by name in ascending order</li> </ul> </div>
Database
Python
import pandas as pd def analyze_organization_hierarchy(employees: pd.DataFrame) -> pd.DataFrame: # Copy the input DataFrame to avoid modifying the original employees = employees.copy() employees["level"] = None # Identify the CEO (level 1) ceo_id = employees.loc[employees["manager_id"].isna(), "employee_id"].values[0] employees.loc[employees["employee_id"] == ceo_id, "level"] = 1 # Recursively compute employee levels def compute_levels(emp_df, level): next_level_ids = emp_df[emp_df["level"] == level]["employee_id"].tolist() if not next_level_ids: return emp_df.loc[emp_df["manager_id"].isin(next_level_ids), "level"] = level + 1 compute_levels(emp_df, level + 1) compute_levels(employees, 1) # Initialize team size and budget dictionaries team_size = {eid: 0 for eid in employees["employee_id"]} budget = { eid: salary for eid, salary in zip(employees["employee_id"], employees["salary"]) } # Compute team size and budget for each employee for eid in sorted(employees["employee_id"], reverse=True): manager_id = employees.loc[ employees["employee_id"] == eid, "manager_id" ].values[0] if pd.notna(manager_id): team_size[manager_id] += team_size[eid] + 1 budget[manager_id] += budget[eid] # Map computed team size and budget to employees DataFrame employees["team_size"] = employees["employee_id"].map(team_size) employees["budget"] = employees["employee_id"].map(budget) # Sort the final result by level (ascending), budget (descending), and employee name (ascending) employees = employees.sort_values( by=["level", "budget", "employee_name"], ascending=[True, False, True] ) return employees[["employee_id", "employee_name", "level", "team_size", "budget"]]
3,482
Analyze Organization Hierarchy
Hard
<p>Table: <code>Employees</code></p> <pre> +----------------+---------+ | Column Name | Type | +----------------+---------+ | employee_id | int | | employee_name | varchar | | manager_id | int | | salary | int | | department | varchar | +----------------+----------+ employee_id is the unique key for this table. Each row contains information about an employee, including their ID, name, their manager&#39;s ID, salary, and department. manager_id is null for the top-level manager (CEO). </pre> <p>Write a solution to analyze the organizational hierarchy and answer the following:</p> <ol> <li><strong>Hierarchy Levels:</strong> For each employee, determine their level in the organization (CEO is level <code>1</code>, employees reporting directly to the CEO are level <code>2</code>, and so on).</li> <li><strong>Team Size:</strong> For each employee who is a manager, count the total number of employees under them (direct and indirect reports).</li> <li><strong>Salary Budget:</strong> For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).</li> </ol> <p>Return <em>the result table ordered by&nbsp;<em>the result ordered by <strong>level</strong> in <strong>ascending</strong> order, then by <strong>budget</strong> in <strong>descending</strong> order, and finally by <strong>employee_name</strong> in <strong>ascending</strong> order</em>.</em></p> <p><em>The result format is in the following example.</em></p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>Employees table:</p> <pre class="example-io"> +-------------+---------------+------------+--------+-------------+ | employee_id | employee_name | manager_id | salary | department | +-------------+---------------+------------+--------+-------------+ | 1 | Alice | null | 12000 | Executive | | 2 | Bob | 1 | 10000 | Sales | | 3 | Charlie | 1 | 10000 | Engineering | | 4 | David | 2 | 7500 | Sales | | 5 | Eva | 2 | 7500 | Sales | | 6 | Frank | 3 | 9000 | Engineering | | 7 | Grace | 3 | 8500 | Engineering | | 8 | Hank | 4 | 6000 | Sales | | 9 | Ivy | 6 | 7000 | Engineering | | 10 | Judy | 6 | 7000 | Engineering | +-------------+---------------+------------+--------+-------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +-------------+---------------+-------+-----------+--------+ | employee_id | employee_name | level | team_size | budget | +-------------+---------------+-------+-----------+--------+ | 1 | Alice | 1 | 9 | 84500 | | 3 | Charlie | 2 | 4 | 41500 | | 2 | Bob | 2 | 3 | 31000 | | 6 | Frank | 3 | 2 | 23000 | | 4 | David | 3 | 1 | 13500 | | 7 | Grace | 3 | 0 | 8500 | | 5 | Eva | 3 | 0 | 7500 | | 9 | Ivy | 4 | 0 | 7000 | | 10 | Judy | 4 | 0 | 7000 | | 8 | Hank | 4 | 0 | 6000 | +-------------+---------------+-------+-----------+--------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>Organization Structure:</strong> <ul> <li>Alice (ID: 1) is the CEO (level 1) with no manager</li> <li>Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)</li> <li>David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)</li> <li>Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)</li> </ul> </li> <li><strong>Level Calculation:</strong> <ul> <li>The CEO (Alice) is at level 1</li> <li>Each subsequent level of management adds 1 to the level</li> </ul> </li> <li><strong>Team Size Calculation:</strong> <ul> <li>Alice has 9 employees under her (the entire company except herself)</li> <li>Bob has 3 employees (David, Eva, and Hank)</li> <li>Charlie has 4 employees (Frank, Grace, Ivy, and Judy)</li> <li>David has 1 employee (Hank)</li> <li>Frank has 2 employees (Ivy and Judy)</li> <li>Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)</li> </ul> </li> <li><strong>Budget Calculation:</strong> <ul> <li>Alice&#39;s budget: Her salary (12000) + all employees&#39; salaries (72500) = 84500</li> <li>Charlie&#39;s budget: His salary (10000) + Frank&#39;s budget (23000) + Grace&#39;s salary (8500) = 41500</li> <li>Bob&#39;s budget: His salary (10000) + David&#39;s budget (13500) + Eva&#39;s salary (7500) = 31000</li> <li>Frank&#39;s budget: His salary (9000) + Ivy&#39;s salary (7000) + Judy&#39;s salary (7000) = 23000</li> <li>David&#39;s budget: His salary (7500) + Hank&#39;s salary (6000) = 13500</li> <li>Employees with no direct reports have budgets equal to their own salary</li> </ul> </li> </ul> <p><strong>Note:</strong></p> <ul> <li>The result is ordered first by level in ascending order</li> <li>Within the same level, employees are ordered by budget in descending order then by name in ascending order</li> </ul> </div>
Database
SQL
# Write your MySQL query statement below WITH RECURSIVE level_cte AS ( SELECT employee_id, manager_id, 1 AS level, salary FROM Employees UNION ALL SELECT a.employee_id, b.manager_id, level + 1, a.salary FROM level_cte a JOIN Employees b ON b.employee_id = a.manager_id ), employee_with_level AS ( SELECT a.employee_id, a.employee_name, a.salary, b.level FROM Employees a, (SELECT employee_id, level FROM level_cte WHERE manager_id IS NULL) b WHERE a.employee_id = b.employee_id ) SELECT a.employee_id, a.employee_name, a.level, COALESCE(b.team_size, 0) AS team_size, a.salary + COALESCE(b.budget, 0) AS budget FROM employee_with_level a LEFT JOIN ( SELECT manager_id AS employee_id, COUNT(*) AS team_size, SUM(salary) AS budget FROM level_cte WHERE manager_id IS NOT NULL GROUP BY manager_id ) b ON a.employee_id = b.employee_id ORDER BY level, budget DESC, employee_name;
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
C++
class Solution { public: int totalNumbers(vector<int>& digits) { unordered_set<int> s; int n = digits.size(); for (int i = 0; i < n; ++i) { if (digits[i] % 2 == 1) { continue; } for (int j = 0; j < n; ++j) { if (i == j) { continue; } for (int k = 0; k < n; ++k) { if (digits[k] == 0 || k == i || k == j) { continue; } s.insert(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size(); } };
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Go
func totalNumbers(digits []int) int { s := make(map[int]struct{}) for i, a := range digits { if a%2 == 1 { continue } for j, b := range digits { if i == j { continue } for k, c := range digits { if c == 0 || k == i || k == j { continue } s[c*100+b*10+a] = struct{}{} } } } return len(s) }
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Java
class Solution { public int totalNumbers(int[] digits) { Set<Integer> s = new HashSet<>(); int n = digits.length; for (int i = 0; i < n; ++i) { if (digits[i] % 2 == 1) { continue; } for (int j = 0; j < n; ++j) { if (i == j) { continue; } for (int k = 0; k < n; ++k) { if (digits[k] == 0 || k == i || k == j) { continue; } s.add(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size(); } }
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
Python
class Solution: def totalNumbers(self, digits: List[int]) -> int: s = set() for i, a in enumerate(digits): if a & 1: continue for j, b in enumerate(digits): if i == j: continue for k, c in enumerate(digits): if c == 0 or k in (i, j): continue s.add(c * 100 + b * 10 + a) return len(s)
3,483
Unique 3-Digit Even Numbers
Easy
<p>You are given an array of digits called <code>digits</code>. Your task is to determine the number of <strong>distinct</strong> three-digit even numbers that can be formed using these digits.</p> <p><strong>Note</strong>: Each <em>copy</em> of a digit can only be used <strong>once per number</strong>, and there may <strong>not</strong> be leading zeros.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,2,3,4]</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong> The 12 distinct 3-digit even numbers that can be formed are 124, 132, 134, 142, 214, 234, 312, 314, 324, 342, 412, and 432. Note that 222 cannot be formed because there is only 1 copy of the digit 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [0,2,2]</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong> The only 3-digit even numbers that can be formed are 202 and 220. Note that the digit 2 can be used twice because it appears twice in the array.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [6,6,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong> Only 666 can be formed.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">digits = [1,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong> No even 3-digit numbers can be formed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= digits.length &lt;= 10</code></li> <li><code>0 &lt;= digits[i] &lt;= 9</code></li> </ul>
Recursion; Array; Hash Table; Enumeration
TypeScript
function totalNumbers(digits: number[]): number { const s = new Set<number>(); const n = digits.length; for (let i = 0; i < n; ++i) { if (digits[i] % 2 === 1) { continue; } for (let j = 0; j < n; ++j) { if (i === j) { continue; } for (let k = 0; k < n; ++k) { if (digits[k] === 0 || k === i || k === j) { continue; } s.add(digits[k] * 100 + digits[j] * 10 + digits[i]); } } } return s.size; }
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
C++
class Spreadsheet { private: unordered_map<string, int> d; public: Spreadsheet(int rows) {} void setCell(string cell, int value) { d[cell] = value; } void resetCell(string cell) { d.erase(cell); } int getValue(string formula) { int ans = 0; stringstream ss(formula.substr(1)); string cell; while (getline(ss, cell, '+')) { if (isdigit(cell[0])) { ans += stoi(cell); } else { ans += d.count(cell) ? d[cell] : 0; } } return ans; } }; /** * Your Spreadsheet object will be instantiated and called as such: * Spreadsheet* obj = new Spreadsheet(rows); * obj->setCell(cell,value); * obj->resetCell(cell); * int param_3 = obj->getValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Go
type Spreadsheet struct { d map[string]int } func Constructor(rows int) Spreadsheet { return Spreadsheet{d: make(map[string]int)} } func (this *Spreadsheet) SetCell(cell string, value int) { this.d[cell] = value } func (this *Spreadsheet) ResetCell(cell string) { delete(this.d, cell) } func (this *Spreadsheet) GetValue(formula string) int { ans := 0 cells := strings.Split(formula[1:], "+") for _, cell := range cells { if val, err := strconv.Atoi(cell); err == nil { ans += val } else { ans += this.d[cell] } } return ans } /** * Your Spreadsheet object will be instantiated and called as such: * obj := Constructor(rows); * obj.SetCell(cell,value); * obj.ResetCell(cell); * param_3 := obj.GetValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Java
class Spreadsheet { private Map<String, Integer> d = new HashMap<>(); public Spreadsheet(int rows) { } public void setCell(String cell, int value) { d.put(cell, value); } public void resetCell(String cell) { d.remove(cell); } public int getValue(String formula) { int ans = 0; for (String cell : formula.substring(1).split("\\+")) { ans += Character.isDigit(cell.charAt(0)) ? Integer.parseInt(cell) : d.getOrDefault(cell, 0); } return ans; } } /** * Your Spreadsheet object will be instantiated and called as such: * Spreadsheet obj = new Spreadsheet(rows); * obj.setCell(cell,value); * obj.resetCell(cell); * int param_3 = obj.getValue(formula); */
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
Python
class Spreadsheet: def __init__(self, rows: int): self.d = {} def setCell(self, cell: str, value: int) -> None: self.d[cell] = value def resetCell(self, cell: str) -> None: self.d.pop(cell, None) def getValue(self, formula: str) -> int: ans = 0 for cell in formula[1:].split("+"): ans += int(cell) if cell[0].isdigit() else self.d.get(cell, 0) return ans # Your Spreadsheet object will be instantiated and called as such: # obj = Spreadsheet(rows) # obj.setCell(cell,value) # obj.resetCell(cell) # param_3 = obj.getValue(formula)
3,484
Design Spreadsheet
Medium
<p>A spreadsheet is a grid with 26 columns (labeled from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and a given number of <code>rows</code>. Each cell in the spreadsheet can hold an integer value between 0 and 10<sup>5</sup>.</p> <p>Implement the <code>Spreadsheet</code> class:</p> <ul> <li><code>Spreadsheet(int rows)</code> Initializes a spreadsheet with 26 columns (labeled <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the specified number of rows. All cells are initially set to 0.</li> <li><code>void setCell(String cell, int value)</code> Sets the value of the specified <code>cell</code>. The cell reference is provided in the format <code>&quot;AX&quot;</code> (e.g., <code>&quot;A1&quot;</code>, <code>&quot;B10&quot;</code>), where the letter represents the column (from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code>) and the number represents a <strong>1-indexed</strong> row.</li> <li><code>void resetCell(String cell)</code> Resets the specified cell to 0.</li> <li><code>int getValue(String formula)</code> Evaluates a formula of the form <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are <strong>either</strong> cell references or non-negative integers, and returns the computed sum.</li> </ul> <p><strong>Note:</strong> If <code>getValue</code> references a cell that has not been explicitly set using <code>setCell</code>, its value is considered 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong><br /> <span class="example-io">[&quot;Spreadsheet&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;setCell&quot;, &quot;getValue&quot;, &quot;resetCell&quot;, &quot;getValue&quot;]<br /> [[3], [&quot;=5+7&quot;], [&quot;A1&quot;, 10], [&quot;=A1+6&quot;], [&quot;B2&quot;, 15], [&quot;=A1+B2&quot;], [&quot;A1&quot;], [&quot;=A1+B2&quot;]]</span></p> <p><strong>Output:</strong><br /> <span class="example-io">[null, 12, null, 16, null, 25, null, 15] </span></p> <p><strong>Explanation</strong></p> Spreadsheet spreadsheet = new Spreadsheet(3); // Initializes a spreadsheet with 3 rows and 26 columns<br data-end="321" data-start="318" /> spreadsheet.getValue(&quot;=5+7&quot;); // returns 12 (5+7)<br data-end="373" data-start="370" /> spreadsheet.setCell(&quot;A1&quot;, 10); // sets A1 to 10<br data-end="423" data-start="420" /> spreadsheet.getValue(&quot;=A1+6&quot;); // returns 16 (10+6)<br data-end="477" data-start="474" /> spreadsheet.setCell(&quot;B2&quot;, 15); // sets B2 to 15<br data-end="527" data-start="524" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 25 (10+15)<br data-end="583" data-start="580" /> spreadsheet.resetCell(&quot;A1&quot;); // resets A1 to 0<br data-end="634" data-start="631" /> spreadsheet.getValue(&quot;=A1+B2&quot;); // returns 15 (0+15)</div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= rows &lt;= 10<sup>3</sup></code></li> <li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li> <li>The formula is always in the format <code>&quot;=X+Y&quot;</code>, where <code>X</code> and <code>Y</code> are either valid cell references or <strong>non-negative</strong> integers with values less than or equal to <code>10<sup>5</sup></code>.</li> <li>Each cell reference consists of a capital letter from <code>&#39;A&#39;</code> to <code>&#39;Z&#39;</code> followed by a row number between <code>1</code> and <code>rows</code>.</li> <li>At most <code>10<sup>4</sup></code> calls will be made in <strong>total</strong> to <code>setCell</code>, <code>resetCell</code>, and <code>getValue</code>.</li> </ul>
Design; Array; Hash Table; String; Matrix
TypeScript
class Spreadsheet { private d: Map<string, number>; constructor(rows: number) { this.d = new Map<string, number>(); } setCell(cell: string, value: number): void { this.d.set(cell, value); } resetCell(cell: string): void { this.d.delete(cell); } getValue(formula: string): number { let ans = 0; const cells = formula.slice(1).split('+'); for (const cell of cells) { ans += isNaN(Number(cell)) ? this.d.get(cell) || 0 : Number(cell); } return ans; } } /** * Your Spreadsheet object will be instantiated and called as such: * var obj = new Spreadsheet(rows) * obj.setCell(cell,value) * obj.resetCell(cell) * var param_3 = obj.getValue(formula) */
3,485
Longest Common Prefix of K Strings After Removal
Hard
<p>You are given an array of strings <code>words</code> and an integer <code>k</code>.</p> <p>For each index <code>i</code> in the range <code>[0, words.length - 1]</code>, find the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> among any <code>k</code> strings (selected at <strong>distinct indices</strong>) from the remaining array after removing the <code>i<sup>th</sup></code> element.</p> <p>Return an array <code>answer</code>, where <code>answer[i]</code> is the answer for <code>i<sup>th</sup></code> element. If removing the <code>i<sup>th</sup></code> element leaves the array with fewer than <code>k</code> strings, <code>answer[i]</code> is 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;jump&quot;,&quot;run&quot;,&quot;run&quot;,&quot;jump&quot;,&quot;run&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4,4,3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing index 0 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;run&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 1 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 2 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 3 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 4 (&quot;run&quot;): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;jump&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;dog&quot;,&quot;racer&quot;,&quot;car&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing any index results in an answer of 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>4</sup></code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>The sum of <code>words[i].length</code> is smaller than or equal <code>10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
C++
class Solution { public: struct TrieNode { int count = 0; int depth = 0; int children[26] = {0}; }; class SegmentTree { public: int n; vector<int> tree; vector<int>& globalCount; SegmentTree(int n, vector<int>& globalCount) : n(n) , globalCount(globalCount) { tree.assign(4 * (n + 1), -1); build(1, 1, n); } void build(int idx, int l, int r) { if (l == r) { tree[idx] = globalCount[l] > 0 ? l : -1; return; } int mid = (l + r) / 2; build(idx * 2, l, mid); build(idx * 2 + 1, mid + 1, r); tree[idx] = max(tree[idx * 2], tree[idx * 2 + 1]); } void update(int idx, int l, int r, int pos, int newVal) { if (l == r) { tree[idx] = newVal > 0 ? l : -1; return; } int mid = (l + r) / 2; if (pos <= mid) update(idx * 2, l, mid, pos, newVal); else update(idx * 2 + 1, mid + 1, r, pos, newVal); tree[idx] = max(tree[idx * 2], tree[idx * 2 + 1]); } int query() { return tree[1]; } }; vector<int> longestCommonPrefix(vector<string>& words, int k) { int n = words.size(); vector<int> ans(n, 0); if (n - 1 < k) return ans; vector<TrieNode> trie(1); for (const string& word : words) { int cur = 0; for (char c : word) { int idx = c - 'a'; if (trie[cur].children[idx] == 0) { trie[cur].children[idx] = trie.size(); trie.push_back({0, trie[cur].depth + 1}); } cur = trie[cur].children[idx]; trie[cur].count++; } } int maxDepth = 0; for (int i = 1; i < trie.size(); ++i) { if (trie[i].count >= k) { maxDepth = max(maxDepth, trie[i].depth); } } vector<int> globalCount(maxDepth + 1, 0); for (int i = 1; i < trie.size(); ++i) { if (trie[i].count >= k && trie[i].depth <= maxDepth) { globalCount[trie[i].depth]++; } } vector<vector<int>> fragileList(n); for (int i = 0; i < n; ++i) { int cur = 0; for (char c : words[i]) { int idx = c - 'a'; cur = trie[cur].children[idx]; if (trie[cur].count == k) { fragileList[i].push_back(trie[cur].depth); } } } int segSize = maxDepth; if (segSize >= 1) { SegmentTree segTree(segSize, globalCount); for (int i = 0; i < n; ++i) { if (n - 1 < k) { ans[i] = 0; } else { for (int d : fragileList[i]) { segTree.update(1, 1, segSize, d, globalCount[d] - 1); } int res = segTree.query(); ans[i] = res == -1 ? 0 : res; for (int d : fragileList[i]) { segTree.update(1, 1, segSize, d, globalCount[d]); } } } } return ans; } };
3,485
Longest Common Prefix of K Strings After Removal
Hard
<p>You are given an array of strings <code>words</code> and an integer <code>k</code>.</p> <p>For each index <code>i</code> in the range <code>[0, words.length - 1]</code>, find the <strong>length</strong> of the <strong>longest common <span data-keyword="string-prefix">prefix</span></strong> among any <code>k</code> strings (selected at <strong>distinct indices</strong>) from the remaining array after removing the <code>i<sup>th</sup></code> element.</p> <p>Return an array <code>answer</code>, where <code>answer[i]</code> is the answer for <code>i<sup>th</sup></code> element. If removing the <code>i<sup>th</sup></code> element leaves the array with fewer than <code>k</code> strings, <code>answer[i]</code> is 0.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;jump&quot;,&quot;run&quot;,&quot;run&quot;,&quot;jump&quot;,&quot;run&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[3,4,4,3,4]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing index 0 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;run&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 1 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 2 (<code>&quot;run&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;jump&quot;, &quot;run&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> <li>Removing index 3 (<code>&quot;jump&quot;</code>): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;run&quot;]</code>. <code>&quot;run&quot;</code> occurs 3 times. Choosing any two gives the longest common prefix <code>&quot;run&quot;</code> (length 3).</li> </ul> </li> <li>Removing index 4 (&quot;run&quot;): <ul> <li><code>words</code> becomes: <code>[&quot;jump&quot;, &quot;run&quot;, &quot;run&quot;, &quot;jump&quot;]</code>. <code>&quot;jump&quot;</code> occurs twice. Choosing these two gives the longest common prefix <code>&quot;jump&quot;</code> (length 4).</li> </ul> </li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">words = [&quot;dog&quot;,&quot;racer&quot;,&quot;car&quot;], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">[0,0,0]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Removing any index results in an answer of 0.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= k &lt;= words.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= words[i].length &lt;= 10<sup>4</sup></code></li> <li><code>words[i]</code> consists of lowercase English letters.</li> <li>The sum of <code>words[i].length</code> is smaller than or equal <code>10<sup>5</sup></code>.</li> </ul>
Trie; Array; String
Java
class Solution { static class TrieNode { int count = 0; int depth = 0; int[] children = new int[26]; TrieNode() { for (int i = 0; i < 26; ++i) children[i] = -1; } } static class SegmentTree { int n; int[] tree; int[] globalCount; SegmentTree(int n, int[] globalCount) { this.n = n; this.globalCount = globalCount; this.tree = new int[4 * (n + 1)]; for (int i = 0; i < tree.length; i++) tree[i] = -1; build(1, 1, n); } void build(int idx, int l, int r) { if (l == r) { tree[idx] = globalCount[l] > 0 ? l : -1; return; } int mid = (l + r) / 2; build(idx * 2, l, mid); build(idx * 2 + 1, mid + 1, r); tree[idx] = Math.max(tree[idx * 2], tree[idx * 2 + 1]); } void update(int idx, int l, int r, int pos, int newVal) { if (l == r) { tree[idx] = newVal > 0 ? l : -1; return; } int mid = (l + r) / 2; if (pos <= mid) { update(idx * 2, l, mid, pos, newVal); } else { update(idx * 2 + 1, mid + 1, r, pos, newVal); } tree[idx] = Math.max(tree[idx * 2], tree[idx * 2 + 1]); } int query() { return tree[1]; } } public int[] longestCommonPrefix(String[] words, int k) { int n = words.length; int[] ans = new int[n]; if (n - 1 < k) return ans; ArrayList<TrieNode> trie = new ArrayList<>(); trie.add(new TrieNode()); for (String word : words) { int cur = 0; for (char c : word.toCharArray()) { int idx = c - 'a'; if (trie.get(cur).children[idx] == -1) { trie.get(cur).children[idx] = trie.size(); TrieNode node = new TrieNode(); node.depth = trie.get(cur).depth + 1; trie.add(node); } cur = trie.get(cur).children[idx]; trie.get(cur).count++; } } int maxDepth = 0; for (int i = 1; i < trie.size(); ++i) { if (trie.get(i).count >= k) { maxDepth = Math.max(maxDepth, trie.get(i).depth); } } int[] globalCount = new int[maxDepth + 1]; for (int i = 1; i < trie.size(); ++i) { TrieNode node = trie.get(i); if (node.count >= k && node.depth <= maxDepth) { globalCount[node.depth]++; } } List<List<Integer>> fragileList = new ArrayList<>(); for (int i = 0; i < n; ++i) { fragileList.add(new ArrayList<>()); } for (int i = 0; i < n; ++i) { int cur = 0; for (char c : words[i].toCharArray()) { int idx = c - 'a'; cur = trie.get(cur).children[idx]; if (trie.get(cur).count == k) { fragileList.get(i).add(trie.get(cur).depth); } } } int segSize = maxDepth; if (segSize >= 1) { SegmentTree segTree = new SegmentTree(segSize, globalCount); for (int i = 0; i < n; ++i) { if (n - 1 < k) { ans[i] = 0; } else { for (int d : fragileList.get(i)) { segTree.update(1, 1, segSize, d, globalCount[d] - 1); } int res = segTree.query(); ans[i] = res == -1 ? 0 : res; for (int d : fragileList.get(i)) { segTree.update(1, 1, segSize, d, globalCount[d]); } } } } return ans; } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
C++
class Solution { public: int maxSum(vector<int>& nums) { int mx = ranges::max(nums); if (mx <= 0) { return mx; } unordered_set<int> s; int ans = 0; for (int x : nums) { if (x < 0 || s.contains(x)) { continue; } ans += x; s.insert(x); } return ans; } };
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
C#
public class Solution { public int MaxSum(int[] nums) { int mx = nums.Max(); if (mx <= 0) { return mx; } HashSet<int> s = new HashSet<int>(); int ans = 0; foreach (int x in nums) { if (x < 0 || s.Contains(x)) { continue; } ans += x; s.Add(x); } return ans; } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Go
func maxSum(nums []int) (ans int) { mx := slices.Max(nums) if mx <= 0 { return mx } s := make(map[int]bool) for _, x := range nums { if x < 0 || s[x] { continue } ans += x s[x] = true } return }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Java
class Solution { public int maxSum(int[] nums) { int mx = Arrays.stream(nums).max().getAsInt(); if (mx <= 0) { return mx; } boolean[] s = new boolean[201]; int ans = 0; for (int x : nums) { if (x < 0 || s[x]) { continue; } ans += x; s[x] = true; } return ans; } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Python
class Solution: def maxSum(self, nums: List[int]) -> int: mx = max(nums) if mx <= 0: return mx ans = 0 s = set() for x in nums: if x < 0 or x in s: continue ans += x s.add(x) return ans
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
Rust
use std::collections::HashSet; impl Solution { pub fn max_sum(nums: Vec<i32>) -> i32 { let mx = *nums.iter().max().unwrap_or(&0); if mx <= 0 { return mx; } let mut s = HashSet::new(); let mut ans = 0; for &x in &nums { if x < 0 || s.contains(&x) { continue; } ans += x; s.insert(x); } ans } }
3,487
Maximum Unique Subarray Sum After Deletion
Easy
<p>You are given an integer array <code>nums</code>.</p> <p>You are allowed to delete any number of elements from <code>nums</code> without making it <strong>empty</strong>. After performing the deletions, select a <span data-keyword="subarray-nonempty">subarray</span> of <code>nums</code> such that:</p> <ol> <li>All elements in the subarray are <strong>unique</strong>.</li> <li>The sum of the elements in the subarray is <strong>maximized</strong>.</li> </ol> <p>Return the <strong>maximum sum</strong> of such a subarray.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4,5]</span></p> <p><strong>Output:</strong> <span class="example-io">15</span></p> <p><strong>Explanation:</strong></p> <p>Select the entire array without deleting any element to obtain the maximum sum.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,1,0,1,1]</span></p> <p><strong>Output:</strong> 1</p> <p><strong>Explanation:</strong></p> <p>Delete the element <code>nums[0] == 1</code>, <code>nums[1] == 1</code>, <code>nums[2] == 0</code>, and <code>nums[3] == 1</code>. Select the entire array <code>[1]</code> to obtain the maximum sum.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,-1,-2,1,0,-1]</span></p> <p><strong>Output:</strong> 3</p> <p><strong>Explanation:</strong></p> <p>Delete the elements <code>nums[2] == -1</code> and <code>nums[3] == -2</code>, and select the subarray <code>[2, 1]</code> from <code>[1, 2, 1, 0, -1]</code> to obtain the maximum sum.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 100</code></li> <li><code>-100 &lt;= nums[i] &lt;= 100</code></li> </ul>
Greedy; Array; Hash Table
TypeScript
function maxSum(nums: number[]): number { const mx = Math.max(...nums); if (mx <= 0) { return mx; } const s = new Set<number>(); let ans: number = 0; for (const x of nums) { if (x < 0 || s.has(x)) { continue; } ans += x; s.add(x); } return ans; }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
C++
class Solution { public: vector<int> solveQueries(vector<int>& nums, vector<int>& queries) { int n = nums.size(); int m = n * 2; vector<int> d(m, m); unordered_map<int, int> left; for (int i = 0; i < m; i++) { int x = nums[i % n]; if (left.count(x)) { d[i] = min(d[i], i - left[x]); } left[x] = i; } unordered_map<int, int> right; for (int i = m - 1; i >= 0; i--) { int x = nums[i % n]; if (right.count(x)) { d[i] = min(d[i], right[x] - i); } right[x] = i; } for (int i = 0; i < n; i++) { d[i] = min(d[i], d[i + n]); } vector<int> ans; for (int query : queries) { ans.push_back(d[query] >= n ? -1 : d[query]); } return ans; } };
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
C#
public class Solution { public IList<int> SolveQueries(int[] nums, int[] queries) { int n = nums.Length; int m = n * 2; int[] d = new int[m]; Array.Fill(d, m); Dictionary<int, int> left = new Dictionary<int, int>(); for (int i = 0; i < m; i++) { int x = nums[i % n]; if (left.ContainsKey(x)) { d[i] = Math.Min(d[i], i - left[x]); } left[x] = i; } Dictionary<int, int> right = new Dictionary<int, int>(); for (int i = m - 1; i >= 0; i--) { int x = nums[i % n]; if (right.ContainsKey(x)) { d[i] = Math.Min(d[i], right[x] - i); } right[x] = i; } for (int i = 0; i < n; i++) { d[i] = Math.Min(d[i], d[i + n]); } List<int> ans = new List<int>(); foreach (int query in queries) { ans.Add(d[query] >= n ? -1 : d[query]); } return ans; } }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Go
func solveQueries(nums []int, queries []int) []int { n := len(nums) m := n * 2 d := make([]int, m) for i := range d { d[i] = m } left := make(map[int]int) for i := 0; i < m; i++ { x := nums[i%n] if idx, exists := left[x]; exists { d[i] = min(d[i], i-idx) } left[x] = i } right := make(map[int]int) for i := m - 1; i >= 0; i-- { x := nums[i%n] if idx, exists := right[x]; exists { d[i] = min(d[i], idx-i) } right[x] = i } for i := 0; i < n; i++ { d[i] = min(d[i], d[i+n]) } ans := make([]int, len(queries)) for i, query := range queries { if d[query] >= n { ans[i] = -1 } else { ans[i] = d[query] } } return ans }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Java
class Solution { public List<Integer> solveQueries(int[] nums, int[] queries) { int n = nums.length; int m = n * 2; int[] d = new int[m]; Arrays.fill(d, m); Map<Integer, Integer> left = new HashMap<>(); for (int i = 0; i < m; i++) { int x = nums[i % n]; if (left.containsKey(x)) { d[i] = Math.min(d[i], i - left.get(x)); } left.put(x, i); } Map<Integer, Integer> right = new HashMap<>(); for (int i = m - 1; i >= 0; i--) { int x = nums[i % n]; if (right.containsKey(x)) { d[i] = Math.min(d[i], right.get(x) - i); } right.put(x, i); } for (int i = 0; i < n; i++) { d[i] = Math.min(d[i], d[i + n]); } List<Integer> ans = new ArrayList<>(); for (int query : queries) { ans.add(d[query] >= n ? -1 : d[query]); } return ans; } }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Python
class Solution: def solveQueries(self, nums: List[int], queries: List[int]) -> List[int]: n = len(nums) m = n << 1 d = [m] * m left = {} for i in range(m): x = nums[i % n] if x in left: d[i] = min(d[i], i - left[x]) left[x] = i right = {} for i in range(m - 1, -1, -1): x = nums[i % n] if x in right: d[i] = min(d[i], right[x] - i) right[x] = i for i in range(n): d[i] = min(d[i], d[i + n]) return [-1 if d[i] >= n else d[i] for i in queries]
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
Rust
use std::collections::HashMap; impl Solution { pub fn solve_queries(nums: Vec<i32>, queries: Vec<i32>) -> Vec<i32> { let n = nums.len(); let m = n * 2; let mut d = vec![m as i32; m]; let mut left = HashMap::new(); for i in 0..m { let x = nums[i % n]; if let Some(&l) = left.get(&x) { d[i] = d[i].min((i - l) as i32); } left.insert(x, i); } let mut right = HashMap::new(); for i in (0..m).rev() { let x = nums[i % n]; if let Some(&r) = right.get(&x) { d[i] = d[i].min((r - i) as i32); } right.insert(x, i); } for i in 0..n { d[i] = d[i].min(d[i + n]); } queries .iter() .map(|&query| { if d[query as usize] >= n as i32 { -1 } else { d[query as usize] } }) .collect() } }
3,488
Closest Equal Element Queries
Medium
<p>You are given a <strong>circular</strong> array <code>nums</code> and an array <code>queries</code>.</p> <p>For each query <code>i</code>, you have to find the following:</p> <ul> <li>The <strong>minimum</strong> distance between the element at index <code>queries[i]</code> and <strong>any</strong> other index <code>j</code> in the <strong>circular</strong> array, where <code>nums[j] == nums[queries[i]]</code>. If no such index exists, the answer for that query should be -1.</li> </ul> <p>Return an array <code>answer</code> of the <strong>same</strong> size as <code>queries</code>, where <code>answer[i]</code> represents the result for query <code>i</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,3,1,4,1,3,2], queries = [0,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">[2,-1,3]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Query 0: The element at <code>queries[0] = 0</code> is <code>nums[0] = 1</code>. The nearest index with the same value is 2, and the distance between them is 2.</li> <li>Query 1: The element at <code>queries[1] = 3</code> is <code>nums[3] = 4</code>. No other index contains 4, so the result is -1.</li> <li>Query 2: The element at <code>queries[2] = 5</code> is <code>nums[5] = 3</code>. The nearest index with the same value is 1, and the distance between them is 3 (following the circular path: <code>5 -&gt; 6 -&gt; 0 -&gt; 1</code>).</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3,4], queries = [0,1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">[-1,-1,-1,-1]</span></p> <p><strong>Explanation:</strong></p> <p>Each value in <code>nums</code> is unique, so no index shares the same value as the queried element. This results in -1 for all queries.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= queries.length &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li> <li><code>0 &lt;= queries[i] &lt; nums.length</code></li> </ul>
Array; Hash Table; Binary Search
TypeScript
function solveQueries(nums: number[], queries: number[]): number[] { const n = nums.length; const m = n * 2; const d: number[] = Array(m).fill(m); const left = new Map<number, number>(); for (let i = 0; i < m; i++) { const x = nums[i % n]; if (left.has(x)) { d[i] = Math.min(d[i], i - left.get(x)!); } left.set(x, i); } const right = new Map<number, number>(); for (let i = m - 1; i >= 0; i--) { const x = nums[i % n]; if (right.has(x)) { d[i] = Math.min(d[i], right.get(x)! - i); } right.set(x, i); } for (let i = 0; i < n; i++) { d[i] = Math.min(d[i], d[i + n]); } return queries.map(query => (d[query] >= n ? -1 : d[query])); }
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
C++
#include <ranges> class Solution { public: bool phonePrefix(vector<string>& numbers) { ranges::sort(numbers, [](const string& a, const string& b) { return a.size() < b.size(); }); for (int i = 0; i < numbers.size(); i++) { if (ranges::any_of(numbers | views::take(i), [&](const string& t) { return numbers[i].starts_with(t); })) { return false; } } return true; } };
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
Go
func phonePrefix(numbers []string) bool { sort.Slice(numbers, func(i, j int) bool { return len(numbers[i]) < len(numbers[j]) }) for i, s := range numbers { for _, t := range numbers[:i] { if strings.HasPrefix(s, t) { return false } } } return true }
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
Java
class Solution { public boolean phonePrefix(String[] numbers) { Arrays.sort(numbers, (a, b) -> Integer.compare(a.length(), b.length())); for (int i = 0; i < numbers.length; i++) { String s = numbers[i]; for (int j = 0; j < i; j++) { if (s.startsWith(numbers[j])) { return false; } } } return true; } }
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
Python
class Solution: def phonePrefix(self, numbers: List[str]) -> bool: numbers.sort(key=len) for i, s in enumerate(numbers): if any(s.startswith(t) for t in numbers[:i]): return False return True
3,491
Phone Number Prefix
Easy
<p>You are given a string array <code>numbers</code> that represents phone numbers. Return <code>true</code> if no phone number is a prefix of any other phone number; otherwise, return <code>false</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;1&quot;,&quot;2&quot;,&quot;4&quot;,&quot;3&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">true</span></p> <p><strong>Explanation:</strong></p> <p>No number is a prefix of another number, so the output is <code>true</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">numbers = [&quot;001&quot;,&quot;007&quot;,&quot;15&quot;,&quot;00153&quot;]</span></p> <p><strong>Output:</strong> <span class="example-io">false</span></p> <p><strong>Explanation:</strong></p> <p>The string <code>&quot;001&quot;</code> is a prefix of the string <code>&quot;00153&quot;</code>. Thus, the output is <code>false</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= numbers.length &lt;= 50</code></li> <li><code>1 &lt;= numbers[i].length &lt;= 50</code></li> <li>All numbers contain only digits <code>&#39;0&#39;</code> to <code>&#39;9&#39;</code>.</li> </ul>
Trie; Array; String; Sorting
TypeScript
function phonePrefix(numbers: string[]): boolean { numbers.sort((a, b) => a.length - b.length); for (let i = 0; i < numbers.length; i++) { for (let j = 0; j < i; j++) { if (numbers[i].startsWith(numbers[j])) { return false; } } } return true; }
3,492
Maximum Containers on a Ship
Easy
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p> <p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship&#39;s maximum weight capacity, <code>maxWeight</code>.</p> <p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation: </strong></p> <p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation: </strong></p> <p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= w &lt;= 1000</code></li> <li><code>1 &lt;= maxWeight &lt;= 10<sup>9</sup></code></li> </ul>
Math
C++
class Solution { public: int maxContainers(int n, int w, int maxWeight) { return min(n * n * w, maxWeight) / w; } };
3,492
Maximum Containers on a Ship
Easy
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p> <p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship&#39;s maximum weight capacity, <code>maxWeight</code>.</p> <p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation: </strong></p> <p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation: </strong></p> <p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= w &lt;= 1000</code></li> <li><code>1 &lt;= maxWeight &lt;= 10<sup>9</sup></code></li> </ul>
Math
Go
func maxContainers(n int, w int, maxWeight int) int { return min(n*n*w, maxWeight) / w }
3,492
Maximum Containers on a Ship
Easy
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p> <p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship&#39;s maximum weight capacity, <code>maxWeight</code>.</p> <p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation: </strong></p> <p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation: </strong></p> <p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= w &lt;= 1000</code></li> <li><code>1 &lt;= maxWeight &lt;= 10<sup>9</sup></code></li> </ul>
Math
Java
class Solution { public int maxContainers(int n, int w, int maxWeight) { return Math.min(n * n * w, maxWeight) / w; } }
3,492
Maximum Containers on a Ship
Easy
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p> <p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship&#39;s maximum weight capacity, <code>maxWeight</code>.</p> <p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation: </strong></p> <p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation: </strong></p> <p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= w &lt;= 1000</code></li> <li><code>1 &lt;= maxWeight &lt;= 10<sup>9</sup></code></li> </ul>
Math
Python
class Solution: def maxContainers(self, n: int, w: int, maxWeight: int) -> int: return min(n * n * w, maxWeight) // w
3,492
Maximum Containers on a Ship
Easy
<p>You are given a positive integer <code>n</code> representing an <code>n x n</code> cargo deck on a ship. Each cell on the deck can hold one container with a weight of <strong>exactly</strong> <code>w</code>.</p> <p>However, the total weight of all containers, if loaded onto the deck, must not exceed the ship&#39;s maximum weight capacity, <code>maxWeight</code>.</p> <p>Return the <strong>maximum</strong> number of containers that can be loaded onto the ship.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 2, w = 3, maxWeight = 15</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation: </strong></p> <p>The deck has 4 cells, and each container weighs 3. The total weight of loading all containers is 12, which does not exceed <code>maxWeight</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">n = 3, w = 5, maxWeight = 20</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation: </strong></p> <p>The deck has 9 cells, and each container weighs 5. The maximum number of containers that can be loaded without exceeding <code>maxWeight</code> is 4.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n &lt;= 1000</code></li> <li><code>1 &lt;= w &lt;= 1000</code></li> <li><code>1 &lt;= maxWeight &lt;= 10<sup>9</sup></code></li> </ul>
Math
TypeScript
function maxContainers(n: number, w: number, maxWeight: number): number { return (Math.min(n * n * w, maxWeight) / w) | 0; }
3,493
Properties Graph
Medium
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p> <p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p> <p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) &gt;= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p> <p>Return the number of <strong>connected components</strong> in the resulting graph.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 3 connected components:</p> <p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 1 connected component:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == properties.length &lt;= 100</code></li> <li><code>1 &lt;= m == properties[i].length &lt;= 100</code></li> <li><code>1 &lt;= properties[i][j] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= m</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
C++
class Solution { public: int numberOfComponents(vector<vector<int>>& properties, int k) { int n = properties.size(); unordered_set<int> ss[n]; vector<int> g[n]; for (int i = 0; i < n; ++i) { for (int x : properties[i]) { ss[i].insert(x); } } for (int i = 0; i < n; ++i) { auto& s1 = ss[i]; for (int j = 0; j < i; ++j) { auto& s2 = ss[j]; int cnt = 0; for (int x : s1) { if (s2.contains(x)) { ++cnt; } } if (cnt >= k) { g[i].push_back(j); g[j].push_back(i); } } } int ans = 0; vector<bool> vis(n); auto dfs = [&](this auto&& dfs, int i) -> void { vis[i] = true; for (int j : g[i]) { if (!vis[j]) { dfs(j); } } }; for (int i = 0; i < n; ++i) { if (!vis[i]) { dfs(i); ++ans; } } return ans; } };
3,493
Properties Graph
Medium
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p> <p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p> <p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) &gt;= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p> <p>Return the number of <strong>connected components</strong> in the resulting graph.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 3 connected components:</p> <p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 1 connected component:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == properties.length &lt;= 100</code></li> <li><code>1 &lt;= m == properties[i].length &lt;= 100</code></li> <li><code>1 &lt;= properties[i][j] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= m</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
Go
func numberOfComponents(properties [][]int, k int) (ans int) { n := len(properties) ss := make([]map[int]struct{}, n) g := make([][]int, n) for i := 0; i < n; i++ { ss[i] = make(map[int]struct{}) for _, x := range properties[i] { ss[i][x] = struct{}{} } } for i := 0; i < n; i++ { for j := 0; j < i; j++ { cnt := 0 for x := range ss[i] { if _, ok := ss[j][x]; ok { cnt++ } } if cnt >= k { g[i] = append(g[i], j) g[j] = append(g[j], i) } } } vis := make([]bool, n) var dfs func(int) dfs = func(i int) { vis[i] = true for _, j := range g[i] { if !vis[j] { dfs(j) } } } for i := 0; i < n; i++ { if !vis[i] { dfs(i) ans++ } } return }
3,493
Properties Graph
Medium
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p> <p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p> <p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) &gt;= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p> <p>Return the number of <strong>connected components</strong> in the resulting graph.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 3 connected components:</p> <p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 1 connected component:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == properties.length &lt;= 100</code></li> <li><code>1 &lt;= m == properties[i].length &lt;= 100</code></li> <li><code>1 &lt;= properties[i][j] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= m</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
Java
class Solution { private List<Integer>[] g; private boolean[] vis; public int numberOfComponents(int[][] properties, int k) { int n = properties.length; g = new List[n]; Set<Integer>[] ss = new Set[n]; Arrays.setAll(g, i -> new ArrayList<>()); Arrays.setAll(ss, i -> new HashSet<>()); for (int i = 0; i < n; ++i) { for (int x : properties[i]) { ss[i].add(x); } } for (int i = 0; i < n; ++i) { for (int j = 0; j < i; ++j) { int cnt = 0; for (int x : ss[i]) { if (ss[j].contains(x)) { ++cnt; } } if (cnt >= k) { g[i].add(j); g[j].add(i); } } } int ans = 0; vis = new boolean[n]; for (int i = 0; i < n; ++i) { if (!vis[i]) { dfs(i); ++ans; } } return ans; } private void dfs(int i) { vis[i] = true; for (int j : g[i]) { if (!vis[j]) { dfs(j); } } } }
3,493
Properties Graph
Medium
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p> <p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p> <p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) &gt;= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p> <p>Return the number of <strong>connected components</strong> in the resulting graph.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 3 connected components:</p> <p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 1 connected component:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == properties.length &lt;= 100</code></li> <li><code>1 &lt;= m == properties[i].length &lt;= 100</code></li> <li><code>1 &lt;= properties[i][j] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= m</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
Python
class Solution: def numberOfComponents(self, properties: List[List[int]], k: int) -> int: def dfs(i: int) -> None: vis[i] = True for j in g[i]: if not vis[j]: dfs(j) n = len(properties) ss = list(map(set, properties)) g = [[] for _ in range(n)] for i, s1 in enumerate(ss): for j in range(i): s2 = ss[j] if len(s1 & s2) >= k: g[i].append(j) g[j].append(i) ans = 0 vis = [False] * n for i in range(n): if not vis[i]: dfs(i) ans += 1 return ans
3,493
Properties Graph
Medium
<p>You are given a 2D integer array <code>properties</code> having dimensions <code>n x m</code> and an integer <code>k</code>.</p> <p>Define a function <code>intersect(a, b)</code> that returns the <strong>number of distinct integers</strong> common to both arrays <code>a</code> and <code>b</code>.</p> <p>Construct an <strong>undirected</strong> graph where each index <code>i</code> corresponds to <code>properties[i]</code>. There is an edge between node <code>i</code> and node <code>j</code> if and only if <code>intersect(properties[i], properties[j]) &gt;= k</code>, where <code>i</code> and <code>j</code> are in the range <code>[0, n - 1]</code> and <code>i != j</code>.</p> <p>Return the number of <strong>connected components</strong> in the resulting graph.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2],[1,1],[3,4],[4,5],[5,6],[7,7]], k = 1</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 3 connected components:</p> <p><img height="171" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/image.png" width="279" /></p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,2,3],[2,3,4],[4,3,5]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The graph formed has 1 connected component:</p> <p><img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3400-3499/3493.Properties%20Graph/images/screenshot-from-2025-02-27-23-58-34.png" style="width: 219px; height: 171px;" /></p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">properties = [[1,1],[1,1]], k = 2</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p><code>intersect(properties[0], properties[1]) = 1</code>, which is less than <code>k</code>. This means there is no edge between <code>properties[0]</code> and <code>properties[1]</code> in the graph.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == properties.length &lt;= 100</code></li> <li><code>1 &lt;= m == properties[i].length &lt;= 100</code></li> <li><code>1 &lt;= properties[i][j] &lt;= 100</code></li> <li><code>1 &lt;= k &lt;= m</code></li> </ul>
Depth-First Search; Breadth-First Search; Union Find; Graph; Array; Hash Table
TypeScript
function numberOfComponents(properties: number[][], k: number): number { const n = properties.length; const ss: Set<number>[] = Array.from({ length: n }, () => new Set()); const g: number[][] = Array.from({ length: n }, () => []); for (let i = 0; i < n; i++) { for (const x of properties[i]) { ss[i].add(x); } } for (let i = 0; i < n; i++) { for (let j = 0; j < i; j++) { let cnt = 0; for (const x of ss[i]) { if (ss[j].has(x)) { cnt++; } } if (cnt >= k) { g[i].push(j); g[j].push(i); } } } let ans = 0; const vis: boolean[] = Array(n).fill(false); const dfs = (i: number) => { vis[i] = true; for (const j of g[i]) { if (!vis[j]) { dfs(j); } } }; for (let i = 0; i < n; i++) { if (!vis[i]) { dfs(i); ans++; } } return ans; }
3,496
Maximize Score After Pair Deletions
Medium
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p> <ul> <li>Remove the first two elements.</li> <li>Remove the last two elements.</li> <li>Remove the first and last element.</li> </ul> <p>For each operation, add the sum of the removed elements to your total score.</p> <p>Return the <strong>maximum</strong> possible score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li> <li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li> <li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li> </ul> <p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li> <li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li> <li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li> </ul> <p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array
C++
class Solution { public: int maxScore(vector<int>& nums) { const int inf = 1 << 30; int n = nums.size(); int s = 0, mi = inf; int t = inf; for (int i = 0; i < n; ++i) { s += nums[i]; mi = min(mi, nums[i]); if (i + 1 < n) { t = min(t, nums[i] + nums[i + 1]); } } if (n % 2 == 1) { return s - mi; } return s - t; } };
3,496
Maximize Score After Pair Deletions
Medium
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p> <ul> <li>Remove the first two elements.</li> <li>Remove the last two elements.</li> <li>Remove the first and last element.</li> </ul> <p>For each operation, add the sum of the removed elements to your total score.</p> <p>Return the <strong>maximum</strong> possible score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li> <li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li> <li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li> </ul> <p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li> <li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li> <li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li> </ul> <p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array
Go
func maxScore(nums []int) int { const inf = 1 << 30 n := len(nums) s, mi, t := 0, inf, inf for i, x := range nums { s += x mi = min(mi, x) if i+1 < n { t = min(t, x+nums[i+1]) } } if n%2 == 1 { return s - mi } return s - t }
3,496
Maximize Score After Pair Deletions
Medium
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p> <ul> <li>Remove the first two elements.</li> <li>Remove the last two elements.</li> <li>Remove the first and last element.</li> </ul> <p>For each operation, add the sum of the removed elements to your total score.</p> <p>Return the <strong>maximum</strong> possible score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li> <li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li> <li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li> </ul> <p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li> <li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li> <li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li> </ul> <p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array
Java
class Solution { public int maxScore(int[] nums) { final int inf = 1 << 30; int n = nums.length; int s = 0, mi = inf; int t = inf; for (int i = 0; i < n; ++i) { s += nums[i]; mi = Math.min(mi, nums[i]); if (i + 1 < n) { t = Math.min(t, nums[i] + nums[i + 1]); } } if (n % 2 == 1) { return s - mi; } return s - t; } }
3,496
Maximize Score After Pair Deletions
Medium
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p> <ul> <li>Remove the first two elements.</li> <li>Remove the last two elements.</li> <li>Remove the first and last element.</li> </ul> <p>For each operation, add the sum of the removed elements to your total score.</p> <p>Return the <strong>maximum</strong> possible score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li> <li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li> <li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li> </ul> <p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li> <li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li> <li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li> </ul> <p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array
Python
class Solution: def maxScore(self, nums: List[int]) -> int: s = sum(nums) if len(nums) & 1: return s - min(nums) return s - min(a + b for a, b in pairwise(nums))
3,496
Maximize Score After Pair Deletions
Medium
<p>You are given an array of integers <code>nums</code>. You <strong>must</strong> repeatedly perform one of the following operations while the array has more than two elements:</p> <ul> <li>Remove the first two elements.</li> <li>Remove the last two elements.</li> <li>Remove the first and last element.</li> </ul> <p>For each operation, add the sum of the removed elements to your total score.</p> <p>Return the <strong>maximum</strong> possible score you can achieve.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [2,4,1]</span></p> <p><strong>Output:</strong> <span class="example-io">6</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first two elements <code>(2 + 4) = 6</code>. The remaining array is <code>[1]</code>.</li> <li>Remove the last two elements <code>(4 + 1) = 5</code>. The remaining array is <code>[2]</code>.</li> <li>Remove the first and last elements <code>(2 + 1) = 3</code>. The remaining array is <code>[4]</code>.</li> </ul> <p>The maximum score is obtained by removing the first two elements, resulting in a final score of 6.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [5,-1,4,2]</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <p>The possible operations are:</p> <ul> <li>Remove the first and last elements <code>(5 + 2) = 7</code>. The remaining array is <code>[-1, 4]</code>.</li> <li>Remove the first two elements <code>(5 + -1) = 4</code>. The remaining array is <code>[4, 2]</code>.</li> <li>Remove the last two elements <code>(4 + 2) = 6</code>. The remaining array is <code>[5, -1]</code>.</li> </ul> <p>The maximum score is obtained by removing the first and last elements, resulting in a total score of 7.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li> </ul>
Greedy; Array
TypeScript
function maxScore(nums: number[]): number { const inf = Infinity; const n = nums.length; let [s, mi, t] = [0, inf, inf]; for (let i = 0; i < n; ++i) { s += nums[i]; mi = Math.min(mi, nums[i]); if (i + 1 < n) { t = Math.min(t, nums[i] + nums[i + 1]); } } return n % 2 ? s - mi : s - t; }
3,497
Analyze Subscription Conversion
Medium
<p>Table: <code>UserActivity</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | user_id | int | | activity_date | date | | activity_type | varchar | | activity_duration| int | +------------------+---------+ (user_id, activity_date, activity_type) is the unique key for this table. activity_type is one of (&#39;free_trial&#39;, &#39;paid&#39;, &#39;cancelled&#39;). activity_duration is the number of minutes the user spent on the platform that day. Each row represents a user&#39;s activity on a specific date. </pre> <p>A subscription service wants to analyze user behavior patterns. The company offers a <code>7</code>-day <strong>free trial</strong>, after which users can subscribe to a <strong>paid plan</strong> or <strong>cancel</strong>. Write a solution to:</p> <ol> <li>Find users who converted from free trial to paid subscription</li> <li>Calculate each user&#39;s <strong>average daily activity duration</strong> during their <strong>free trial</strong> period (rounded to <code>2</code> decimal places)</li> <li>Calculate each user&#39;s <strong>average daily activity duration</strong> during their <strong>paid</strong> subscription period (rounded to <code>2</code> decimal places)</li> </ol> <p>Return <em>the result table ordered by </em><code>user_id</code><em> in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>UserActivity table:</p> <pre class="example-io"> +---------+---------------+---------------+-------------------+ | user_id | activity_date | activity_type | activity_duration | +---------+---------------+---------------+-------------------+ | 1 | 2023-01-01 | free_trial | 45 | | 1 | 2023-01-02 | free_trial | 30 | | 1 | 2023-01-05 | free_trial | 60 | | 1 | 2023-01-10 | paid | 75 | | 1 | 2023-01-12 | paid | 90 | | 1 | 2023-01-15 | paid | 65 | | 2 | 2023-02-01 | free_trial | 55 | | 2 | 2023-02-03 | free_trial | 25 | | 2 | 2023-02-07 | free_trial | 50 | | 2 | 2023-02-10 | cancelled | 0 | | 3 | 2023-03-05 | free_trial | 70 | | 3 | 2023-03-06 | free_trial | 60 | | 3 | 2023-03-08 | free_trial | 80 | | 3 | 2023-03-12 | paid | 50 | | 3 | 2023-03-15 | paid | 55 | | 3 | 2023-03-20 | paid | 85 | | 4 | 2023-04-01 | free_trial | 40 | | 4 | 2023-04-03 | free_trial | 35 | | 4 | 2023-04-05 | paid | 45 | | 4 | 2023-04-07 | cancelled | 0 | +---------+---------------+---------------+-------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+--------------------+-------------------+ | user_id | trial_avg_duration | paid_avg_duration | +---------+--------------------+-------------------+ | 1 | 45.00 | 76.67 | | 3 | 70.00 | 63.33 | | 4 | 37.50 | 45.00 | +---------+--------------------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>User 1:</strong> <ul> <li>Had 3 days of free trial with durations of 45, 30, and 60 minutes.</li> <li>Average trial duration: (45 + 30 + 60) / 3 = 45.00 minutes.</li> <li>Had 3 days of paid subscription with durations of 75, 90, and 65 minutes.</li> <li>Average paid duration: (75 + 90 + 65) / 3 = 76.67 minutes.</li> </ul> </li> <li><strong>User 2:</strong> <ul> <li>Had 3 days of free trial with durations of 55, 25, and 50 minutes.</li> <li>Average trial duration: (55 + 25 + 50) / 3 = 43.33 minutes.</li> <li>Did not convert to a paid subscription (only had free_trial and cancelled activities).</li> <li>Not included in the output because they didn&#39;t convert to paid.</li> </ul> </li> <li><strong>User 3:</strong> <ul> <li>Had 3 days of free trial with durations of 70, 60, and 80 minutes.</li> <li>Average trial duration: (70 + 60 + 80) / 3 = 70.00 minutes.</li> <li>Had 3 days of paid subscription with durations of 50, 55, and 85 minutes.</li> <li>Average paid duration: (50 + 55 + 85) / 3 = 63.33 minutes.</li> </ul> </li> <li><strong>User 4:</strong> <ul> <li>Had 2 days of free trial with durations of 40 and 35 minutes.</li> <li>Average trial duration: (40 + 35) / 2 = 37.50 minutes.</li> <li>Had 1 day of paid subscription with duration of 45 minutes before cancelling.</li> <li>Average paid duration: 45.00 minutes.</li> </ul> </li> </ul> <p>The result table only includes users who converted from free trial to paid subscription (users 1, 3, and 4), and is ordered by user_id in ascending order.</p> </div>
Database
Python
import pandas as pd def analyze_subscription_conversion(user_activity: pd.DataFrame) -> pd.DataFrame: df = user_activity[user_activity["activity_type"] != "cancelled"] df_grouped = ( df.groupby(["user_id", "activity_type"])["activity_duration"] .mean() .add(0.0001) .round(2) .reset_index() ) df_free_trial = ( df_grouped[df_grouped["activity_type"] == "free_trial"] .rename(columns={"activity_duration": "trial_avg_duration"}) .drop(columns=["activity_type"]) ) df_paid = ( df_grouped[df_grouped["activity_type"] == "paid"] .rename(columns={"activity_duration": "paid_avg_duration"}) .drop(columns=["activity_type"]) ) result = df_free_trial.merge(df_paid, on="user_id", how="inner").sort_values( "user_id" ) return result
3,497
Analyze Subscription Conversion
Medium
<p>Table: <code>UserActivity</code></p> <pre> +------------------+---------+ | Column Name | Type | +------------------+---------+ | user_id | int | | activity_date | date | | activity_type | varchar | | activity_duration| int | +------------------+---------+ (user_id, activity_date, activity_type) is the unique key for this table. activity_type is one of (&#39;free_trial&#39;, &#39;paid&#39;, &#39;cancelled&#39;). activity_duration is the number of minutes the user spent on the platform that day. Each row represents a user&#39;s activity on a specific date. </pre> <p>A subscription service wants to analyze user behavior patterns. The company offers a <code>7</code>-day <strong>free trial</strong>, after which users can subscribe to a <strong>paid plan</strong> or <strong>cancel</strong>. Write a solution to:</p> <ol> <li>Find users who converted from free trial to paid subscription</li> <li>Calculate each user&#39;s <strong>average daily activity duration</strong> during their <strong>free trial</strong> period (rounded to <code>2</code> decimal places)</li> <li>Calculate each user&#39;s <strong>average daily activity duration</strong> during their <strong>paid</strong> subscription period (rounded to <code>2</code> decimal places)</li> </ol> <p>Return <em>the result table ordered by </em><code>user_id</code><em> in <strong>ascending</strong> order</em>.</p> <p>The result format is in the following example.</p> <p>&nbsp;</p> <p><strong class="example">Example:</strong></p> <div class="example-block"> <p><strong>Input:</strong></p> <p>UserActivity table:</p> <pre class="example-io"> +---------+---------------+---------------+-------------------+ | user_id | activity_date | activity_type | activity_duration | +---------+---------------+---------------+-------------------+ | 1 | 2023-01-01 | free_trial | 45 | | 1 | 2023-01-02 | free_trial | 30 | | 1 | 2023-01-05 | free_trial | 60 | | 1 | 2023-01-10 | paid | 75 | | 1 | 2023-01-12 | paid | 90 | | 1 | 2023-01-15 | paid | 65 | | 2 | 2023-02-01 | free_trial | 55 | | 2 | 2023-02-03 | free_trial | 25 | | 2 | 2023-02-07 | free_trial | 50 | | 2 | 2023-02-10 | cancelled | 0 | | 3 | 2023-03-05 | free_trial | 70 | | 3 | 2023-03-06 | free_trial | 60 | | 3 | 2023-03-08 | free_trial | 80 | | 3 | 2023-03-12 | paid | 50 | | 3 | 2023-03-15 | paid | 55 | | 3 | 2023-03-20 | paid | 85 | | 4 | 2023-04-01 | free_trial | 40 | | 4 | 2023-04-03 | free_trial | 35 | | 4 | 2023-04-05 | paid | 45 | | 4 | 2023-04-07 | cancelled | 0 | +---------+---------------+---------------+-------------------+ </pre> <p><strong>Output:</strong></p> <pre class="example-io"> +---------+--------------------+-------------------+ | user_id | trial_avg_duration | paid_avg_duration | +---------+--------------------+-------------------+ | 1 | 45.00 | 76.67 | | 3 | 70.00 | 63.33 | | 4 | 37.50 | 45.00 | +---------+--------------------+-------------------+ </pre> <p><strong>Explanation:</strong></p> <ul> <li><strong>User 1:</strong> <ul> <li>Had 3 days of free trial with durations of 45, 30, and 60 minutes.</li> <li>Average trial duration: (45 + 30 + 60) / 3 = 45.00 minutes.</li> <li>Had 3 days of paid subscription with durations of 75, 90, and 65 minutes.</li> <li>Average paid duration: (75 + 90 + 65) / 3 = 76.67 minutes.</li> </ul> </li> <li><strong>User 2:</strong> <ul> <li>Had 3 days of free trial with durations of 55, 25, and 50 minutes.</li> <li>Average trial duration: (55 + 25 + 50) / 3 = 43.33 minutes.</li> <li>Did not convert to a paid subscription (only had free_trial and cancelled activities).</li> <li>Not included in the output because they didn&#39;t convert to paid.</li> </ul> </li> <li><strong>User 3:</strong> <ul> <li>Had 3 days of free trial with durations of 70, 60, and 80 minutes.</li> <li>Average trial duration: (70 + 60 + 80) / 3 = 70.00 minutes.</li> <li>Had 3 days of paid subscription with durations of 50, 55, and 85 minutes.</li> <li>Average paid duration: (50 + 55 + 85) / 3 = 63.33 minutes.</li> </ul> </li> <li><strong>User 4:</strong> <ul> <li>Had 2 days of free trial with durations of 40 and 35 minutes.</li> <li>Average trial duration: (40 + 35) / 2 = 37.50 minutes.</li> <li>Had 1 day of paid subscription with duration of 45 minutes before cancelling.</li> <li>Average paid duration: 45.00 minutes.</li> </ul> </li> </ul> <p>The result table only includes users who converted from free trial to paid subscription (users 1, 3, and 4), and is ordered by user_id in ascending order.</p> </div>
Database
SQL
# Write your MySQL query statement below WITH T AS ( SELECT user_id, activity_type, ROUND(SUM(activity_duration) / COUNT(1), 2) duration FROM UserActivity WHERE activity_type != 'cancelled' GROUP BY user_id, activity_type ), F AS ( SELECT user_id, duration trial_avg_duration FROM T WHERE activity_type = 'free_trial' ), P AS ( SELECT user_id, duration paid_avg_duration FROM T WHERE activity_type = 'paid' ) SELECT user_id, trial_avg_duration, paid_avg_duration FROM F JOIN P USING (user_id) ORDER BY 1;
3,498
Reverse Degree of a String
Easy
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p> <p>The <strong>reverse degree</strong> is calculated as follows:</p> <ol> <li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>&#39;a&#39;</code> = 26, <code>&#39;b&#39;</code> = 25, ..., <code>&#39;z&#39;</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li> <li>Sum these products for all characters in the string.</li> </ol> <p>Return the <strong>reverse degree</strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">148</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">26</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;b&#39;</code></td> <td style="border: 1px solid black;">25</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">50</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;c&#39;</code></td> <td style="border: 1px solid black;">24</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">72</td> </tr> </tbody> </table> <p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaza&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">160</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">52</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">4</td> <td style="border: 1px solid black;">104</td> </tr> </tbody> </table> <p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> contains only lowercase English letters.</li> </ul>
String; Simulation
C++
class Solution { public: int reverseDegree(string s) { int n = s.length(); int ans = 0; for (int i = 1; i <= n; ++i) { int x = 26 - (s[i - 1] - 'a'); ans += i * x; } return ans; } };
3,498
Reverse Degree of a String
Easy
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p> <p>The <strong>reverse degree</strong> is calculated as follows:</p> <ol> <li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>&#39;a&#39;</code> = 26, <code>&#39;b&#39;</code> = 25, ..., <code>&#39;z&#39;</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li> <li>Sum these products for all characters in the string.</li> </ol> <p>Return the <strong>reverse degree</strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">148</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">26</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;b&#39;</code></td> <td style="border: 1px solid black;">25</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">50</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;c&#39;</code></td> <td style="border: 1px solid black;">24</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">72</td> </tr> </tbody> </table> <p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaza&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">160</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">52</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">4</td> <td style="border: 1px solid black;">104</td> </tr> </tbody> </table> <p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> contains only lowercase English letters.</li> </ul>
String; Simulation
Go
func reverseDegree(s string) (ans int) { for i, c := range s { x := 26 - int(c-'a') ans += (i + 1) * x } return }
3,498
Reverse Degree of a String
Easy
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p> <p>The <strong>reverse degree</strong> is calculated as follows:</p> <ol> <li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>&#39;a&#39;</code> = 26, <code>&#39;b&#39;</code> = 25, ..., <code>&#39;z&#39;</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li> <li>Sum these products for all characters in the string.</li> </ol> <p>Return the <strong>reverse degree</strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">148</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">26</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;b&#39;</code></td> <td style="border: 1px solid black;">25</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">50</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;c&#39;</code></td> <td style="border: 1px solid black;">24</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">72</td> </tr> </tbody> </table> <p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaza&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">160</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">52</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">4</td> <td style="border: 1px solid black;">104</td> </tr> </tbody> </table> <p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> contains only lowercase English letters.</li> </ul>
String; Simulation
Java
class Solution { public int reverseDegree(String s) { int n = s.length(); int ans = 0; for (int i = 1; i <= n; ++i) { int x = 26 - (s.charAt(i - 1) - 'a'); ans += i * x; } return ans; } }
3,498
Reverse Degree of a String
Easy
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p> <p>The <strong>reverse degree</strong> is calculated as follows:</p> <ol> <li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>&#39;a&#39;</code> = 26, <code>&#39;b&#39;</code> = 25, ..., <code>&#39;z&#39;</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li> <li>Sum these products for all characters in the string.</li> </ol> <p>Return the <strong>reverse degree</strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">148</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">26</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;b&#39;</code></td> <td style="border: 1px solid black;">25</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">50</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;c&#39;</code></td> <td style="border: 1px solid black;">24</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">72</td> </tr> </tbody> </table> <p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaza&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">160</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">52</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">4</td> <td style="border: 1px solid black;">104</td> </tr> </tbody> </table> <p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> contains only lowercase English letters.</li> </ul>
String; Simulation
Python
class Solution: def reverseDegree(self, s: str) -> int: ans = 0 for i, c in enumerate(s, 1): x = 26 - (ord(c) - ord("a")) ans += i * x return ans
3,498
Reverse Degree of a String
Easy
<p>Given a string <code>s</code>, calculate its <strong>reverse degree</strong>.</p> <p>The <strong>reverse degree</strong> is calculated as follows:</p> <ol> <li>For each character, multiply its position in the <em>reversed</em> alphabet (<code>&#39;a&#39;</code> = 26, <code>&#39;b&#39;</code> = 25, ..., <code>&#39;z&#39;</code> = 1) with its position in the string <strong>(1-indexed)</strong>.</li> <li>Sum these products for all characters in the string.</li> </ol> <p>Return the <strong>reverse degree</strong> of <code>s</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">148</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">26</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;b&#39;</code></td> <td style="border: 1px solid black;">25</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">50</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;c&#39;</code></td> <td style="border: 1px solid black;">24</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">72</td> </tr> </tbody> </table> <p>The reversed degree is <code>26 + 50 + 72 = 148</code>.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;zaza&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">160</span></p> <p><strong>Explanation:</strong></p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Letter</th> <th style="border: 1px solid black;">Index in Reversed Alphabet</th> <th style="border: 1px solid black;">Index in String</th> <th style="border: 1px solid black;">Product</th> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">1</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">2</td> <td style="border: 1px solid black;">52</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;z&#39;</code></td> <td style="border: 1px solid black;">1</td> <td style="border: 1px solid black;">3</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;"><code>&#39;a&#39;</code></td> <td style="border: 1px solid black;">26</td> <td style="border: 1px solid black;">4</td> <td style="border: 1px solid black;">104</td> </tr> </tbody> </table> <p>The reverse degree is <code>1 + 52 + 3 + 104 = 160</code>.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length &lt;= 1000</code></li> <li><code>s</code> contains only lowercase English letters.</li> </ul>
String; Simulation
TypeScript
function reverseDegree(s: string): number { let ans = 0; for (let i = 1; i <= s.length; ++i) { const x = 26 - (s.charCodeAt(i - 1) - 'a'.charCodeAt(0)); ans += i * x; } return ans; }
3,499
Maximize Active Section with Trade I
Medium
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p> <ul> <li><code>&#39;1&#39;</code> represents an <strong>active</strong> section.</li> <li><code>&#39;0&#39;</code> represents an <strong>inactive</strong> section.</li> </ul> <p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p> <ul> <li>Convert a contiguous block of <code>&#39;1&#39;</code>s that is surrounded by <code>&#39;0&#39;</code>s to all <code>&#39;0&#39;</code>s.</li> <li>Afterward, convert a contiguous block of <code>&#39;0&#39;</code>s that is surrounded by <code>&#39;1&#39;</code>s to all <code>&#39;1&#39;</code>s.</li> </ul> <p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p> <p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>&#39;1&#39;</code> at both ends, forming <code>t = &#39;1&#39; + s + &#39;1&#39;</code>. The augmented <code>&#39;1&#39;</code>s <strong>do not</strong> contribute to the final count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Because there is no block of <code>&#39;1&#39;</code>s surrounded by <code>&#39;0&#39;</code>s, no valid trade is possible. The maximum number of active sections is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;0100&quot;</code> &rarr; Augmented to <code>&quot;101001&quot;</code>.</li> <li>Choose <code>&quot;0100&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;1<u><strong>0000</strong></u>1&quot;</code> &rarr; <code>&quot;1<u><strong>1111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1000100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;1000100&quot;</code> &rarr; Augmented to <code>&quot;110001001&quot;</code>.</li> <li>Choose <code>&quot;000100&quot;</code>, convert <code>&quot;11000<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;11<u><strong>000000</strong></u>1&quot;</code> &rarr; <code>&quot;11<u><strong>111111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111111&quot;</code>. The maximum number of active sections is 7.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01010&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;01010&quot;</code> &rarr; Augmented to <code>&quot;1010101&quot;</code>.</li> <li>Choose <code>&quot;010&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>0101&quot;</code> &rarr; <code>&quot;1<u><strong>000</strong></u>101&quot;</code> &rarr; <code>&quot;1<u><strong>111</strong></u>101&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;11110&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
String; Enumeration
C++
class Solution { public: int maxActiveSectionsAfterTrade(std::string s) { int n = s.length(); int ans = 0, i = 0; int pre = INT_MIN, mx = 0; while (i < n) { int j = i + 1; while (j < n && s[j] == s[i]) { j++; } int cur = j - i; if (s[i] == '1') { ans += cur; } else { mx = std::max(mx, pre + cur); pre = cur; } i = j; } ans += mx; return ans; } };
3,499
Maximize Active Section with Trade I
Medium
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p> <ul> <li><code>&#39;1&#39;</code> represents an <strong>active</strong> section.</li> <li><code>&#39;0&#39;</code> represents an <strong>inactive</strong> section.</li> </ul> <p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p> <ul> <li>Convert a contiguous block of <code>&#39;1&#39;</code>s that is surrounded by <code>&#39;0&#39;</code>s to all <code>&#39;0&#39;</code>s.</li> <li>Afterward, convert a contiguous block of <code>&#39;0&#39;</code>s that is surrounded by <code>&#39;1&#39;</code>s to all <code>&#39;1&#39;</code>s.</li> </ul> <p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p> <p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>&#39;1&#39;</code> at both ends, forming <code>t = &#39;1&#39; + s + &#39;1&#39;</code>. The augmented <code>&#39;1&#39;</code>s <strong>do not</strong> contribute to the final count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Because there is no block of <code>&#39;1&#39;</code>s surrounded by <code>&#39;0&#39;</code>s, no valid trade is possible. The maximum number of active sections is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;0100&quot;</code> &rarr; Augmented to <code>&quot;101001&quot;</code>.</li> <li>Choose <code>&quot;0100&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;1<u><strong>0000</strong></u>1&quot;</code> &rarr; <code>&quot;1<u><strong>1111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1000100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;1000100&quot;</code> &rarr; Augmented to <code>&quot;110001001&quot;</code>.</li> <li>Choose <code>&quot;000100&quot;</code>, convert <code>&quot;11000<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;11<u><strong>000000</strong></u>1&quot;</code> &rarr; <code>&quot;11<u><strong>111111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111111&quot;</code>. The maximum number of active sections is 7.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01010&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;01010&quot;</code> &rarr; Augmented to <code>&quot;1010101&quot;</code>.</li> <li>Choose <code>&quot;010&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>0101&quot;</code> &rarr; <code>&quot;1<u><strong>000</strong></u>101&quot;</code> &rarr; <code>&quot;1<u><strong>111</strong></u>101&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;11110&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
String; Enumeration
Go
func maxActiveSectionsAfterTrade(s string) (ans int) { n := len(s) pre, mx := math.MinInt, 0 for i := 0; i < n; { j := i + 1 for j < n && s[j] == s[i] { j++ } cur := j - i if s[i] == '1' { ans += cur } else { mx = max(mx, pre+cur) pre = cur } i = j } ans += mx return }
3,499
Maximize Active Section with Trade I
Medium
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p> <ul> <li><code>&#39;1&#39;</code> represents an <strong>active</strong> section.</li> <li><code>&#39;0&#39;</code> represents an <strong>inactive</strong> section.</li> </ul> <p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p> <ul> <li>Convert a contiguous block of <code>&#39;1&#39;</code>s that is surrounded by <code>&#39;0&#39;</code>s to all <code>&#39;0&#39;</code>s.</li> <li>Afterward, convert a contiguous block of <code>&#39;0&#39;</code>s that is surrounded by <code>&#39;1&#39;</code>s to all <code>&#39;1&#39;</code>s.</li> </ul> <p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p> <p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>&#39;1&#39;</code> at both ends, forming <code>t = &#39;1&#39; + s + &#39;1&#39;</code>. The augmented <code>&#39;1&#39;</code>s <strong>do not</strong> contribute to the final count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Because there is no block of <code>&#39;1&#39;</code>s surrounded by <code>&#39;0&#39;</code>s, no valid trade is possible. The maximum number of active sections is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;0100&quot;</code> &rarr; Augmented to <code>&quot;101001&quot;</code>.</li> <li>Choose <code>&quot;0100&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;1<u><strong>0000</strong></u>1&quot;</code> &rarr; <code>&quot;1<u><strong>1111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1000100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;1000100&quot;</code> &rarr; Augmented to <code>&quot;110001001&quot;</code>.</li> <li>Choose <code>&quot;000100&quot;</code>, convert <code>&quot;11000<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;11<u><strong>000000</strong></u>1&quot;</code> &rarr; <code>&quot;11<u><strong>111111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111111&quot;</code>. The maximum number of active sections is 7.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01010&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;01010&quot;</code> &rarr; Augmented to <code>&quot;1010101&quot;</code>.</li> <li>Choose <code>&quot;010&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>0101&quot;</code> &rarr; <code>&quot;1<u><strong>000</strong></u>101&quot;</code> &rarr; <code>&quot;1<u><strong>111</strong></u>101&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;11110&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
String; Enumeration
Java
class Solution { public int maxActiveSectionsAfterTrade(String s) { int n = s.length(); int ans = 0, i = 0; int pre = Integer.MIN_VALUE, mx = 0; while (i < n) { int j = i + 1; while (j < n && s.charAt(j) == s.charAt(i)) { j++; } int cur = j - i; if (s.charAt(i) == '1') { ans += cur; } else { mx = Math.max(mx, pre + cur); pre = cur; } i = j; } ans += mx; return ans; } }
3,499
Maximize Active Section with Trade I
Medium
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p> <ul> <li><code>&#39;1&#39;</code> represents an <strong>active</strong> section.</li> <li><code>&#39;0&#39;</code> represents an <strong>inactive</strong> section.</li> </ul> <p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p> <ul> <li>Convert a contiguous block of <code>&#39;1&#39;</code>s that is surrounded by <code>&#39;0&#39;</code>s to all <code>&#39;0&#39;</code>s.</li> <li>Afterward, convert a contiguous block of <code>&#39;0&#39;</code>s that is surrounded by <code>&#39;1&#39;</code>s to all <code>&#39;1&#39;</code>s.</li> </ul> <p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p> <p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>&#39;1&#39;</code> at both ends, forming <code>t = &#39;1&#39; + s + &#39;1&#39;</code>. The augmented <code>&#39;1&#39;</code>s <strong>do not</strong> contribute to the final count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Because there is no block of <code>&#39;1&#39;</code>s surrounded by <code>&#39;0&#39;</code>s, no valid trade is possible. The maximum number of active sections is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;0100&quot;</code> &rarr; Augmented to <code>&quot;101001&quot;</code>.</li> <li>Choose <code>&quot;0100&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;1<u><strong>0000</strong></u>1&quot;</code> &rarr; <code>&quot;1<u><strong>1111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1000100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;1000100&quot;</code> &rarr; Augmented to <code>&quot;110001001&quot;</code>.</li> <li>Choose <code>&quot;000100&quot;</code>, convert <code>&quot;11000<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;11<u><strong>000000</strong></u>1&quot;</code> &rarr; <code>&quot;11<u><strong>111111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111111&quot;</code>. The maximum number of active sections is 7.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01010&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;01010&quot;</code> &rarr; Augmented to <code>&quot;1010101&quot;</code>.</li> <li>Choose <code>&quot;010&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>0101&quot;</code> &rarr; <code>&quot;1<u><strong>000</strong></u>101&quot;</code> &rarr; <code>&quot;1<u><strong>111</strong></u>101&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;11110&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
String; Enumeration
Python
class Solution: def maxActiveSectionsAfterTrade(self, s: str) -> int: n = len(s) ans = i = 0 pre, mx = -inf, 0 while i < n: j = i + 1 while j < n and s[j] == s[i]: j += 1 cur = j - i if s[i] == "1": ans += cur else: mx = max(mx, pre + cur) pre = cur i = j ans += mx return ans
3,499
Maximize Active Section with Trade I
Medium
<p>You are given a binary string <code>s</code> of length <code>n</code>, where:</p> <ul> <li><code>&#39;1&#39;</code> represents an <strong>active</strong> section.</li> <li><code>&#39;0&#39;</code> represents an <strong>inactive</strong> section.</li> </ul> <p>You can perform <strong>at most one trade</strong> to maximize the number of active sections in <code>s</code>. In a trade, you:</p> <ul> <li>Convert a contiguous block of <code>&#39;1&#39;</code>s that is surrounded by <code>&#39;0&#39;</code>s to all <code>&#39;0&#39;</code>s.</li> <li>Afterward, convert a contiguous block of <code>&#39;0&#39;</code>s that is surrounded by <code>&#39;1&#39;</code>s to all <code>&#39;1&#39;</code>s.</li> </ul> <p>Return the <strong>maximum</strong> number of active sections in <code>s</code> after making the optimal trade.</p> <p><strong>Note:</strong> Treat <code>s</code> as if it is <strong>augmented</strong> with a <code>&#39;1&#39;</code> at both ends, forming <code>t = &#39;1&#39; + s + &#39;1&#39;</code>. The augmented <code>&#39;1&#39;</code>s <strong>do not</strong> contribute to the final count.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Because there is no block of <code>&#39;1&#39;</code>s surrounded by <code>&#39;0&#39;</code>s, no valid trade is possible. The maximum number of active sections is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;0100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;0100&quot;</code> &rarr; Augmented to <code>&quot;101001&quot;</code>.</li> <li>Choose <code>&quot;0100&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;1<u><strong>0000</strong></u>1&quot;</code> &rarr; <code>&quot;1<u><strong>1111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;1000100&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">7</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;1000100&quot;</code> &rarr; Augmented to <code>&quot;110001001&quot;</code>.</li> <li>Choose <code>&quot;000100&quot;</code>, convert <code>&quot;11000<u><strong>1</strong></u>001&quot;</code> &rarr; <code>&quot;11<u><strong>000000</strong></u>1&quot;</code> &rarr; <code>&quot;11<u><strong>111111</strong></u>1&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;1111111&quot;</code>. The maximum number of active sections is 7.</li> </ul> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;01010&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>String <code>&quot;01010&quot;</code> &rarr; Augmented to <code>&quot;1010101&quot;</code>.</li> <li>Choose <code>&quot;010&quot;</code>, convert <code>&quot;10<u><strong>1</strong></u>0101&quot;</code> &rarr; <code>&quot;1<u><strong>000</strong></u>101&quot;</code> &rarr; <code>&quot;1<u><strong>111</strong></u>101&quot;</code>.</li> <li>The final string without augmentation is <code>&quot;11110&quot;</code>. The maximum number of active sections is 4.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == s.length &lt;= 10<sup>5</sup></code></li> <li><code>s[i]</code> is either <code>&#39;0&#39;</code> or <code>&#39;1&#39;</code></li> </ul>
String; Enumeration
TypeScript
function maxActiveSectionsAfterTrade(s: string): number { let n = s.length; let [ans, mx] = [0, 0]; let pre = Number.MIN_SAFE_INTEGER; for (let i = 0; i < n; ) { let j = i + 1; while (j < n && s[j] === s[i]) { j++; } let cur = j - i; if (s[i] === '1') { ans += cur; } else { mx = Math.max(mx, pre + cur); pre = cur; } i = j; } ans += mx; return ans; }
3,502
Minimum Cost to Reach Every Position
Easy
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p> <p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p> <p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p> <ul data-end="632" data-start="488"> <li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li> <li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li> </ul> <p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can get to each position in the following way:</p> <ul> <li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li> <li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li> <li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li> <li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li> <li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li> <li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == cost.length &lt;= 100</code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array
C++
class Solution { public: vector<int> minCosts(vector<int>& cost) { int n = cost.size(); vector<int> ans(n); int mi = cost[0]; for (int i = 0; i < n; ++i) { mi = min(mi, cost[i]); ans[i] = mi; } return ans; } };
3,502
Minimum Cost to Reach Every Position
Easy
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p> <p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p> <p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p> <ul data-end="632" data-start="488"> <li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li> <li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li> </ul> <p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can get to each position in the following way:</p> <ul> <li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li> <li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li> <li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li> <li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li> <li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li> <li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == cost.length &lt;= 100</code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array
Go
func minCosts(cost []int) []int { n := len(cost) ans := make([]int, n) mi := cost[0] for i, c := range cost { mi = min(mi, c) ans[i] = mi } return ans }
3,502
Minimum Cost to Reach Every Position
Easy
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p> <p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p> <p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p> <ul data-end="632" data-start="488"> <li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li> <li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li> </ul> <p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can get to each position in the following way:</p> <ul> <li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li> <li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li> <li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li> <li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li> <li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li> <li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == cost.length &lt;= 100</code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array
Java
class Solution { public int[] minCosts(int[] cost) { int n = cost.length; int[] ans = new int[n]; int mi = cost[0]; for (int i = 0; i < n; ++i) { mi = Math.min(mi, cost[i]); ans[i] = mi; } return ans; } }
3,502
Minimum Cost to Reach Every Position
Easy
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p> <p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p> <p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p> <ul data-end="632" data-start="488"> <li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li> <li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li> </ul> <p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can get to each position in the following way:</p> <ul> <li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li> <li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li> <li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li> <li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li> <li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li> <li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == cost.length &lt;= 100</code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array
Python
class Solution: def minCosts(self, cost: List[int]) -> List[int]: n = len(cost) ans = [0] * n mi = cost[0] for i, c in enumerate(cost): mi = min(mi, c) ans[i] = mi return ans
3,502
Minimum Cost to Reach Every Position
Easy
<p data-end="438" data-start="104">You are given an integer array <code data-end="119" data-start="113">cost</code> of size <code data-end="131" data-start="128">n</code>. You are currently at position <code data-end="166" data-start="163">n</code> (at the end of the line) in a line of <code data-end="187" data-start="180">n + 1</code> people (numbered from 0 to <code data-end="218" data-start="215">n</code>).</p> <p data-end="438" data-start="104">You wish to move forward in the line, but each person in front of you charges a specific amount to <strong>swap</strong> places. The cost to swap with person <code data-end="375" data-start="372">i</code> is given by <code data-end="397" data-start="388">cost[i]</code>.</p> <p data-end="487" data-start="440">You are allowed to swap places with people as follows:</p> <ul data-end="632" data-start="488"> <li data-end="572" data-start="488">If they are in front of you, you <strong>must</strong> pay them <code data-end="546" data-start="537">cost[i]</code> to swap with them.</li> <li data-end="632" data-start="573">If they are behind you, they can swap with you for free.</li> </ul> <p data-end="755" data-start="634">Return an array <code>answer</code> of size <code>n</code>, where <code>answer[i]</code> is the <strong data-end="680" data-start="664">minimum</strong> total cost to reach each position <code>i</code> in the line<font face="monospace">.</font></p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [5,3,4,1,3,2]</span></p> <p><strong>Output:</strong> <span class="example-io">[5,3,3,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can get to each position in the following way:</p> <ul> <li><code>i = 0</code>. We can swap with person 0 for a cost of 5.</li> <li><span class="example-io"><code><font face="monospace">i = </font>1</code>. We can swap with person 1 for a cost of 3.</span></li> <li><span class="example-io"><code>i = 2</code>. We can swap with person 1 for a cost of 3, then swap with person 2 for free.</span></li> <li><span class="example-io"><code>i = 3</code>. We can swap with person 3 for a cost of 1.</span></li> <li><span class="example-io"><code>i = 4</code>. We can swap with person 3 for a cost of 1, then swap with person 4 for free.</span></li> <li><span class="example-io"><code>i = 5</code>. We can swap with person 3 for a cost of 1, then swap with person 5 for free.</span></li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">cost = [1,2,4,6,7]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,1,1,1,1]</span></p> <p><strong>Explanation:</strong></p> <p>We can swap with person 0 for a cost of <span class="example-io">1, then we will be able to reach any position <code>i</code> for free.</span></p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= n == cost.length &lt;= 100</code></li> <li><code>1 &lt;= cost[i] &lt;= 100</code></li> </ul>
Array
TypeScript
function minCosts(cost: number[]): number[] { const n = cost.length; const ans: number[] = Array(n).fill(0); let mi = cost[0]; for (let i = 0; i < n; ++i) { mi = Math.min(mi, cost[i]); ans[i] = mi; } return ans; }
3,503
Longest Palindrome After Substring Concatenation I
Medium
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> 5</p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 30</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming; Enumeration
C++
class Solution { public: int longestPalindrome(string s, string t) { int m = s.size(), n = t.size(); ranges::reverse(t); vector<int> g1 = calc(s), g2 = calc(t); int ans = max(ranges::max(g1), ranges::max(g2)); vector<vector<int>> f(m + 1, vector<int>(n + 1)); for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (s[i - 1] == t[j - 1]) { f[i][j] = f[i - 1][j - 1] + 1; ans = max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0)); ans = max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0)); } } } return ans; } private: void expand(const string& s, vector<int>& g, int l, int r) { while (l >= 0 && r < s.size() && s[l] == s[r]) { g[l] = max(g[l], r - l + 1); --l; ++r; } } vector<int> calc(const string& s) { int n = s.size(); vector<int> g(n, 0); for (int i = 0; i < n; ++i) { expand(s, g, i, i); expand(s, g, i, i + 1); } return g; } };
3,503
Longest Palindrome After Substring Concatenation I
Medium
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> 5</p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 30</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming; Enumeration
Go
func longestPalindrome(s, t string) int { m, n := len(s), len(t) t = reverse(t) g1, g2 := calc(s), calc(t) ans := max(slices.Max(g1), slices.Max(g2)) f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { if s[i-1] == t[j-1] { f[i][j] = f[i-1][j-1] + 1 a, b := 0, 0 if i < m { a = g1[i] } if j < n { b = g2[j] } ans = max(ans, f[i][j]*2+a) ans = max(ans, f[i][j]*2+b) } } } return ans } func calc(s string) []int { n, g := len(s), make([]int, len(s)) for i := 0; i < n; i++ { expand(s, g, i, i) expand(s, g, i, i+1) } return g } func expand(s string, g []int, l, r int) { for l >= 0 && r < len(s) && s[l] == s[r] { g[l] = max(g[l], r-l+1) l, r = l-1, r+1 } } func reverse(s string) string { r := []rune(s) slices.Reverse(r) return string(r) }
3,503
Longest Palindrome After Substring Concatenation I
Medium
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> 5</p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 30</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming; Enumeration
Java
class Solution { public int longestPalindrome(String S, String T) { char[] s = S.toCharArray(); char[] t = new StringBuilder(T).reverse().toString().toCharArray(); int m = s.length, n = t.length; int[] g1 = calc(s), g2 = calc(t); int ans = Math.max(Arrays.stream(g1).max().getAsInt(), Arrays.stream(g2).max().getAsInt()); int[][] f = new int[m + 1][n + 1]; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (s[i - 1] == t[j - 1]) { f[i][j] = f[i - 1][j - 1] + 1; ans = Math.max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0)); ans = Math.max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0)); } } } return ans; } private void expand(char[] s, int[] g, int l, int r) { while (l >= 0 && r < s.length && s[l] == s[r]) { g[l] = Math.max(g[l], r - l + 1); --l; ++r; } } private int[] calc(char[] s) { int n = s.length; int[] g = new int[n]; for (int i = 0; i < n; ++i) { expand(s, g, i, i); expand(s, g, i, i + 1); } return g; } }
3,503
Longest Palindrome After Substring Concatenation I
Medium
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> 5</p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 30</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming; Enumeration
Python
class Solution: def longestPalindrome(self, s: str, t: str) -> int: def expand(s: str, g: List[int], l: int, r: int): while l >= 0 and r < len(s) and s[l] == s[r]: g[l] = max(g[l], r - l + 1) l, r = l - 1, r + 1 def calc(s: str) -> List[int]: n = len(s) g = [0] * n for i in range(n): expand(s, g, i, i) expand(s, g, i, i + 1) return g m, n = len(s), len(t) t = t[::-1] g1, g2 = calc(s), calc(t) ans = max(*g1, *g2) f = [[0] * (n + 1) for _ in range(m + 1)] for i, a in enumerate(s, 1): for j, b in enumerate(t, 1): if a == b: f[i][j] = f[i - 1][j - 1] + 1 ans = max(ans, f[i][j] * 2 + (0 if i >= m else g1[i])) ans = max(ans, f[i][j] * 2 + (0 if j >= n else g2[j])) return ans
3,503
Longest Palindrome After Substring Concatenation I
Medium
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> 4</p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> 5</p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 30</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming; Enumeration
TypeScript
function longestPalindrome(s: string, t: string): number { function expand(s: string, g: number[], l: number, r: number): void { while (l >= 0 && r < s.length && s[l] === s[r]) { g[l] = Math.max(g[l], r - l + 1); l--; r++; } } function calc(s: string): number[] { const n = s.length; const g: number[] = Array(n).fill(0); for (let i = 0; i < n; i++) { expand(s, g, i, i); expand(s, g, i, i + 1); } return g; } const m = s.length, n = t.length; t = t.split('').reverse().join(''); const g1 = calc(s); const g2 = calc(t); let ans = Math.max(...g1, ...g2); const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { if (s[i - 1] === t[j - 1]) { f[i][j] = f[i - 1][j - 1] + 1; ans = Math.max(ans, f[i][j] * 2 + (i >= m ? 0 : g1[i])); ans = Math.max(ans, f[i][j] * 2 + (j >= n ? 0 : g2[j])); } } } return ans; }
3,504
Longest Palindrome After Substring Concatenation II
Hard
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
C++
class Solution { public: int longestPalindrome(string s, string t) { int m = s.size(), n = t.size(); ranges::reverse(t); vector<int> g1 = calc(s), g2 = calc(t); int ans = max(ranges::max(g1), ranges::max(g2)); vector<vector<int>> f(m + 1, vector<int>(n + 1)); for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (s[i - 1] == t[j - 1]) { f[i][j] = f[i - 1][j - 1] + 1; ans = max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0)); ans = max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0)); } } } return ans; } private: void expand(const string& s, vector<int>& g, int l, int r) { while (l >= 0 && r < s.size() && s[l] == s[r]) { g[l] = max(g[l], r - l + 1); --l; ++r; } } vector<int> calc(const string& s) { int n = s.size(); vector<int> g(n, 0); for (int i = 0; i < n; ++i) { expand(s, g, i, i); expand(s, g, i, i + 1); } return g; } };
3,504
Longest Palindrome After Substring Concatenation II
Hard
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
Go
func longestPalindrome(s, t string) int { m, n := len(s), len(t) t = reverse(t) g1, g2 := calc(s), calc(t) ans := max(slices.Max(g1), slices.Max(g2)) f := make([][]int, m+1) for i := range f { f[i] = make([]int, n+1) } for i := 1; i <= m; i++ { for j := 1; j <= n; j++ { if s[i-1] == t[j-1] { f[i][j] = f[i-1][j-1] + 1 a, b := 0, 0 if i < m { a = g1[i] } if j < n { b = g2[j] } ans = max(ans, f[i][j]*2+a) ans = max(ans, f[i][j]*2+b) } } } return ans } func calc(s string) []int { n, g := len(s), make([]int, len(s)) for i := 0; i < n; i++ { expand(s, g, i, i) expand(s, g, i, i+1) } return g } func expand(s string, g []int, l, r int) { for l >= 0 && r < len(s) && s[l] == s[r] { g[l] = max(g[l], r-l+1) l, r = l-1, r+1 } } func reverse(s string) string { r := []rune(s) slices.Reverse(r) return string(r) }
3,504
Longest Palindrome After Substring Concatenation II
Hard
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
Java
class Solution { public int longestPalindrome(String S, String T) { char[] s = S.toCharArray(); char[] t = new StringBuilder(T).reverse().toString().toCharArray(); int m = s.length, n = t.length; int[] g1 = calc(s), g2 = calc(t); int ans = Math.max(Arrays.stream(g1).max().getAsInt(), Arrays.stream(g2).max().getAsInt()); int[][] f = new int[m + 1][n + 1]; for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { if (s[i - 1] == t[j - 1]) { f[i][j] = f[i - 1][j - 1] + 1; ans = Math.max(ans, f[i][j] * 2 + (i < m ? g1[i] : 0)); ans = Math.max(ans, f[i][j] * 2 + (j < n ? g2[j] : 0)); } } } return ans; } private void expand(char[] s, int[] g, int l, int r) { while (l >= 0 && r < s.length && s[l] == s[r]) { g[l] = Math.max(g[l], r - l + 1); --l; ++r; } } private int[] calc(char[] s) { int n = s.length; int[] g = new int[n]; for (int i = 0; i < n; ++i) { expand(s, g, i, i); expand(s, g, i, i + 1); } return g; } }
3,504
Longest Palindrome After Substring Concatenation II
Hard
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
Python
class Solution: def longestPalindrome(self, s: str, t: str) -> int: def expand(s: str, g: List[int], l: int, r: int): while l >= 0 and r < len(s) and s[l] == s[r]: g[l] = max(g[l], r - l + 1) l, r = l - 1, r + 1 def calc(s: str) -> List[int]: n = len(s) g = [0] * n for i in range(n): expand(s, g, i, i) expand(s, g, i, i + 1) return g m, n = len(s), len(t) t = t[::-1] g1, g2 = calc(s), calc(t) ans = max(*g1, *g2) f = [[0] * (n + 1) for _ in range(m + 1)] for i, a in enumerate(s, 1): for j, b in enumerate(t, 1): if a == b: f[i][j] = f[i - 1][j - 1] + 1 ans = max(ans, f[i][j] * 2 + (0 if i >= m else g1[i])) ans = max(ans, f[i][j] * 2 + (0 if j >= n else g2[j])) return ans
3,504
Longest Palindrome After Substring Concatenation II
Hard
<p>You are given two strings, <code>s</code> and <code>t</code>.</p> <p>You can create a new string by selecting a <span data-keyword="substring">substring</span> from <code>s</code> (possibly empty) and a substring from <code>t</code> (possibly empty), then concatenating them <strong>in order</strong>.</p> <p>Return the length of the <strong>longest</strong> <span data-keyword="palindrome-string">palindrome</span> that can be formed this way.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;a&quot;, t = &quot;a&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;a&quot;</code> from <code>s</code> and <code>&quot;a&quot;</code> from <code>t</code> results in <code>&quot;aa&quot;</code>, which is a palindrome of length 2.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abc&quot;, t = &quot;def&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Since all characters are different, the longest palindrome is any single character, so the answer is 1.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;b&quot;, t = &quot;aaaa&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <p>Selecting &quot;<code>aaaa</code>&quot; from <code>t</code> is the longest palindrome, so the answer is 4.</p> </div> <p><strong class="example">Example 4:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">s = &quot;abcde&quot;, t = &quot;ecdba&quot;</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <p>Concatenating <code>&quot;abc&quot;</code> from <code>s</code> and <code>&quot;ba&quot;</code> from <code>t</code> results in <code>&quot;abcba&quot;</code>, which is a palindrome of length 5.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li> <li><code>s</code> and <code>t</code> consist of lowercase English letters.</li> </ul>
Two Pointers; String; Dynamic Programming
TypeScript
function longestPalindrome(s: string, t: string): number { function expand(s: string, g: number[], l: number, r: number): void { while (l >= 0 && r < s.length && s[l] === s[r]) { g[l] = Math.max(g[l], r - l + 1); l--; r++; } } function calc(s: string): number[] { const n = s.length; const g: number[] = Array(n).fill(0); for (let i = 0; i < n; i++) { expand(s, g, i, i); expand(s, g, i, i + 1); } return g; } const m = s.length, n = t.length; t = t.split('').reverse().join(''); const g1 = calc(s); const g2 = calc(t); let ans = Math.max(...g1, ...g2); const f: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0)); for (let i = 1; i <= m; i++) { for (let j = 1; j <= n; j++) { if (s[i - 1] === t[j - 1]) { f[i][j] = f[i - 1][j - 1] + 1; ans = Math.max(ans, f[i][j] * 2 + (i >= m ? 0 : g1[i])); ans = Math.max(ans, f[i][j] * 2 + (j >= n ? 0 : g2[j])); } } } return ans; }
3,506
Find Time Required to Eliminate Bacterial Strains
Hard
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p> <p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body&#39;s survival.</p> <p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p> <p>The WBC devises a clever strategy to fight the bacteria:</p> <ul> <li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li> <li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li> <li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li> <li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li> </ul> <p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p> <p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li> <li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p> <p><strong>Output:</strong>15</p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timeReq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= timeReq[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= splitTime &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Heap (Priority Queue)
C++
class Solution { public: long long minEliminationTime(vector<int>& timeReq, int splitTime) { using ll = long long; priority_queue<ll, vector<ll>, greater<ll>> pq; for (int v : timeReq) { pq.push(v); } while (pq.size() > 1) { pq.pop(); ll x = pq.top(); pq.pop(); pq.push(x + splitTime); } return pq.top(); } };
3,506
Find Time Required to Eliminate Bacterial Strains
Hard
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p> <p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body&#39;s survival.</p> <p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p> <p>The WBC devises a clever strategy to fight the bacteria:</p> <ul> <li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li> <li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li> <li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li> <li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li> </ul> <p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p> <p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li> <li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p> <p><strong>Output:</strong>15</p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timeReq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= timeReq[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= splitTime &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Heap (Priority Queue)
Go
func minEliminationTime(timeReq []int, splitTime int) int64 { pq := hp{} for _, v := range timeReq { heap.Push(&pq, v) } for pq.Len() > 1 { heap.Pop(&pq) heap.Push(&pq, heap.Pop(&pq).(int)+splitTime) } return int64(pq.IntSlice[0]) } type hp struct{ sort.IntSlice } func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) } func (h *hp) Pop() any { a := h.IntSlice v := a[len(a)-1] h.IntSlice = a[:len(a)-1] return v }
3,506
Find Time Required to Eliminate Bacterial Strains
Hard
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p> <p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body&#39;s survival.</p> <p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p> <p>The WBC devises a clever strategy to fight the bacteria:</p> <ul> <li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li> <li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li> <li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li> <li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li> </ul> <p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p> <p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li> <li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p> <p><strong>Output:</strong>15</p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timeReq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= timeReq[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= splitTime &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Heap (Priority Queue)
Java
class Solution { public long minEliminationTime(int[] timeReq, int splitTime) { PriorityQueue<Long> q = new PriorityQueue<>(); for (int x : timeReq) { q.offer((long) x); } while (q.size() > 1) { q.poll(); q.offer(q.poll() + splitTime); } return q.poll(); } }
3,506
Find Time Required to Eliminate Bacterial Strains
Hard
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p> <p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body&#39;s survival.</p> <p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p> <p>The WBC devises a clever strategy to fight the bacteria:</p> <ul> <li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li> <li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li> <li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li> <li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li> </ul> <p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p> <p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li> <li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p> <p><strong>Output:</strong>15</p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timeReq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= timeReq[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= splitTime &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Heap (Priority Queue)
Python
class Solution: def minEliminationTime(self, timeReq: List[int], splitTime: int) -> int: heapify(timeReq) while len(timeReq) > 1: heappop(timeReq) heappush(timeReq, heappop(timeReq) + splitTime) return timeReq[0]
3,506
Find Time Required to Eliminate Bacterial Strains
Hard
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p> <p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body&#39;s survival.</p> <p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p> <p>The WBC devises a clever strategy to fight the bacteria:</p> <ul> <li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li> <li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li> <li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li> <li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li> </ul> <p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p> <p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li> <li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p> <p><strong>Output:</strong>15</p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timeReq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= timeReq[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= splitTime &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Heap (Priority Queue)
Rust
use std::cmp::Reverse; use std::collections::BinaryHeap; impl Solution { pub fn min_elimination_time(time_req: Vec<i32>, split_time: i32) -> i64 { let mut pq = BinaryHeap::new(); for x in time_req { pq.push(Reverse(x as i64)); } while pq.len() > 1 { pq.pop(); let merged = pq.pop().unwrap().0 + split_time as i64; pq.push(Reverse(merged)); } pq.pop().unwrap().0 } }
3,506
Find Time Required to Eliminate Bacterial Strains
Hard
<p>You are given an integer array <code>timeReq</code> and an integer <code>splitTime</code>.</p> <p>In the microscopic world of the human body, the immune system faces an extraordinary challenge: combatting a rapidly multiplying bacterial colony that threatens the body&#39;s survival.</p> <p>Initially, only one <strong>white blood cell</strong> (<strong>WBC</strong>) is deployed to eliminate the bacteria. However, the lone WBC quickly realizes it cannot keep up with the bacterial growth rate.</p> <p>The WBC devises a clever strategy to fight the bacteria:</p> <ul> <li>The <code>i<sup>th</sup></code> bacterial strain takes <code>timeReq[i]</code> units of time to be eliminated.</li> <li>A single WBC can eliminate <strong>only one</strong> bacterial strain. Afterwards, the WBC is exhausted and cannot perform any other tasks.</li> <li>A WBC can split itself into two WBCs, but this requires <code>splitTime</code> units of time. Once split, the two WBCs can work in <strong>parallel</strong> on eliminating the bacteria.</li> <li><em>Only one</em> WBC can work on a single bacterial strain. Multiple WBCs <strong>cannot</strong> attack one strain in parallel.</li> </ul> <p>You must determine the <strong>minimum</strong> time required to eliminate all the bacterial strains.</p> <p><strong>Note</strong> that the bacterial strains can be eliminated in any order.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4,5], splitTime = 2</span></p> <p><strong>Output:</strong> <span class="example-io">12</span></p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 2 units of time.</li> <li>One of the WBCs eliminates strain 0 at a time <code>t = 2 + 10 = 12.</code> The other WBC splits again, using 2 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 2 + 2 + 4</code> and <code>t = 2 + 2 + 5</code>.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">timeReq = [10,4], splitTime = 5</span></p> <p><strong>Output:</strong>15</p> <p><strong>Explanation:</strong></p> <p>The elimination process goes as follows:</p> <ul> <li>Initially, there is a single WBC. The WBC splits into 2 WBCs after 5 units of time.</li> <li>The 2 new WBCs eliminate the bacteria at times <code>t = 5 + 10</code> and <code>t = 5 + 4</code>.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 &lt;= timeReq.length &lt;= 10<sup>5</sup></code></li> <li><code>1 &lt;= timeReq[i] &lt;= 10<sup>9</sup></code></li> <li><code>1 &lt;= splitTime &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Math; Heap (Priority Queue)
TypeScript
function minEliminationTime(timeReq: number[], splitTime: number): number { const pq = new MinPriorityQueue(); for (const b of timeReq) { pq.enqueue(b); } while (pq.size() > 1) { pq.dequeue()!; pq.enqueue(pq.dequeue()! + splitTime); } return pq.dequeue()!; }
3,511
Make a Positive Array
Medium
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li> </ul> <p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarrays with more than 2 elements and a non-positive sum are:</p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Subarray Indices</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> <th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th> <th style="border: 1px solid black;">New Sum</th> </tr> <tr> <td style="border: 1px solid black;">nums[0...2]</td> <td style="border: 1px solid black;">[-1, -2, 3]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[-1, 1, 3]</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">nums[0...3]</td> <td style="border: 1px solid black;">[-1, -2, 3, -1]</td> <td style="border: 1px solid black;">-1</td> <td style="border: 1px solid black;">[-1, 1, 3, -1]</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">nums[1...3]</td> <td style="border: 1px solid black;">[-2, 3, -1]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[1, 3, -1]</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>Thus, <code>nums</code> is positive after one operation.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already positive, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Prefix Sum
C++
class Solution { public: int makeArrayPositive(vector<int>& nums) { int ans = 0; long long preMx = 0, s = 0; for (int l = -1, r = 0; r < nums.size(); r++) { int x = nums[r]; s += x; if (r - l > 2 && s <= preMx) { ans++; l = r; preMx = s = 0; } else if (r - l >= 2) { preMx = max(preMx, s - x - nums[r - 1]); } } return ans; } };
3,511
Make a Positive Array
Medium
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li> </ul> <p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarrays with more than 2 elements and a non-positive sum are:</p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Subarray Indices</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> <th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th> <th style="border: 1px solid black;">New Sum</th> </tr> <tr> <td style="border: 1px solid black;">nums[0...2]</td> <td style="border: 1px solid black;">[-1, -2, 3]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[-1, 1, 3]</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">nums[0...3]</td> <td style="border: 1px solid black;">[-1, -2, 3, -1]</td> <td style="border: 1px solid black;">-1</td> <td style="border: 1px solid black;">[-1, 1, 3, -1]</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">nums[1...3]</td> <td style="border: 1px solid black;">[-2, 3, -1]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[1, 3, -1]</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>Thus, <code>nums</code> is positive after one operation.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already positive, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Prefix Sum
Go
func makeArrayPositive(nums []int) (ans int) { l := -1 preMx := 0 s := 0 for r, x := range nums { s += x if r-l > 2 && s <= preMx { ans++ l = r preMx = 0 s = 0 } else if r-l >= 2 { preMx = max(preMx, s-x-nums[r-1]) } } return }
3,511
Make a Positive Array
Medium
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li> </ul> <p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarrays with more than 2 elements and a non-positive sum are:</p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Subarray Indices</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> <th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th> <th style="border: 1px solid black;">New Sum</th> </tr> <tr> <td style="border: 1px solid black;">nums[0...2]</td> <td style="border: 1px solid black;">[-1, -2, 3]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[-1, 1, 3]</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">nums[0...3]</td> <td style="border: 1px solid black;">[-1, -2, 3, -1]</td> <td style="border: 1px solid black;">-1</td> <td style="border: 1px solid black;">[-1, 1, 3, -1]</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">nums[1...3]</td> <td style="border: 1px solid black;">[-2, 3, -1]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[1, 3, -1]</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>Thus, <code>nums</code> is positive after one operation.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already positive, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Prefix Sum
Java
class Solution { public int makeArrayPositive(int[] nums) { int ans = 0; long preMx = 0, s = 0; for (int l = -1, r = 0; r < nums.length; r++) { int x = nums[r]; s += x; if (r - l > 2 && s <= preMx) { ans++; l = r; preMx = s = 0; } else if (r - l >= 2) { preMx = Math.max(preMx, s - x - nums[r - 1]); } } return ans; } }
3,511
Make a Positive Array
Medium
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li> </ul> <p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarrays with more than 2 elements and a non-positive sum are:</p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Subarray Indices</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> <th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th> <th style="border: 1px solid black;">New Sum</th> </tr> <tr> <td style="border: 1px solid black;">nums[0...2]</td> <td style="border: 1px solid black;">[-1, -2, 3]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[-1, 1, 3]</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">nums[0...3]</td> <td style="border: 1px solid black;">[-1, -2, 3, -1]</td> <td style="border: 1px solid black;">-1</td> <td style="border: 1px solid black;">[-1, 1, 3, -1]</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">nums[1...3]</td> <td style="border: 1px solid black;">[-2, 3, -1]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[1, 3, -1]</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>Thus, <code>nums</code> is positive after one operation.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already positive, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Prefix Sum
Python
class Solution: def makeArrayPositive(self, nums: List[int]) -> int: l = -1 ans = pre_mx = s = 0 for r, x in enumerate(nums): s += x if r - l > 2 and s <= pre_mx: ans += 1 l = r pre_mx = s = 0 elif r - l >= 2: pre_mx = max(pre_mx, s - x - nums[r - 1]) return ans
3,511
Make a Positive Array
Medium
<p>You are given an array <code>nums</code>. An array is considered <strong>positive</strong> if the sum of all numbers in each <strong><span data-keyword="subarray">subarray</span></strong> with <strong>more than two</strong> elements is positive.</p> <p>You can perform the following operation any number of times:</p> <ul> <li>Replace <strong>one</strong> element in <code>nums</code> with any integer between -10<sup>18</sup> and 10<sup>18</sup>.</li> </ul> <p>Find the <strong>minimum</strong> number of operations needed to make <code>nums</code> <strong>positive</strong>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-10,15,-12]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarray with more than 2 elements is the array itself. The sum of all elements is <code>(-10) + 15 + (-12) = -7</code>. By replacing <code>nums[0]</code> with 0, the new sum becomes <code>0 + 15 + (-12) = 3</code>. Thus, the array is now positive.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [-1,-2,3,-1,2,6]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>The only subarrays with more than 2 elements and a non-positive sum are:</p> <table style="border: 1px solid black;"> <tbody> <tr> <th style="border: 1px solid black;">Subarray Indices</th> <th style="border: 1px solid black;">Subarray</th> <th style="border: 1px solid black;">Sum</th> <th style="border: 1px solid black;">Subarray After Replacement (Set nums[1] = 1)</th> <th style="border: 1px solid black;">New Sum</th> </tr> <tr> <td style="border: 1px solid black;">nums[0...2]</td> <td style="border: 1px solid black;">[-1, -2, 3]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[-1, 1, 3]</td> <td style="border: 1px solid black;">3</td> </tr> <tr> <td style="border: 1px solid black;">nums[0...3]</td> <td style="border: 1px solid black;">[-1, -2, 3, -1]</td> <td style="border: 1px solid black;">-1</td> <td style="border: 1px solid black;">[-1, 1, 3, -1]</td> <td style="border: 1px solid black;">2</td> </tr> <tr> <td style="border: 1px solid black;">nums[1...3]</td> <td style="border: 1px solid black;">[-2, 3, -1]</td> <td style="border: 1px solid black;">0</td> <td style="border: 1px solid black;">[1, 3, -1]</td> <td style="border: 1px solid black;">3</td> </tr> </tbody> </table> <p>Thus, <code>nums</code> is positive after one operation.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [1,2,3]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>The array is already positive, so no operations are needed.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>3 &lt;= nums.length &lt;= 10<sup>5</sup></code></li> <li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li> </ul>
Greedy; Array; Prefix Sum
TypeScript
function makeArrayPositive(nums: number[]): number { let l = -1; let [ans, preMx, s] = [0, 0, 0]; for (let r = 0; r < nums.length; r++) { const x = nums[r]; s += x; if (r - l > 2 && s <= preMx) { ans++; l = r; preMx = 0; s = 0; } else if (r - l >= 2) { preMx = Math.max(preMx, s - x - nums[r - 1]); } } return ans; }
3,512
Minimum Operations to Make Array Sum Divisible by K
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p> <ul> <li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li> </ul> <p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li> <li>The sum is 15, which is divisible by 5.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li> <li>The sum is 0, which is divisible by 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Math
C++
class Solution { public: int minOperations(vector<int>& nums, int k) { return reduce(nums.begin(), nums.end(), 0) % k; } };
3,512
Minimum Operations to Make Array Sum Divisible by K
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p> <ul> <li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li> </ul> <p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li> <li>The sum is 15, which is divisible by 5.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li> <li>The sum is 0, which is divisible by 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Math
Go
func minOperations(nums []int, k int) (ans int) { for _, x := range nums { ans = (ans + x) % k } return }
3,512
Minimum Operations to Make Array Sum Divisible by K
Easy
<p>You are given an integer array <code>nums</code> and an integer <code>k</code>. You can perform the following operation any number of times:</p> <ul> <li>Select an index <code>i</code> and replace <code>nums[i]</code> with <code>nums[i] - 1</code>.</li> </ul> <p>Return the <strong>minimum</strong> number of operations required to make the sum of the array divisible by <code>k</code>.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,9,7], k = 5</span></p> <p><strong>Output:</strong> <span class="example-io">4</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform 4 operations on <code>nums[1] = 9</code>. Now, <code>nums = [3, 5, 7]</code>.</li> <li>The sum is 15, which is divisible by 5.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [4,1,3], k = 4</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul> <li>The sum is 8, which is already divisible by 4. Hence, no operations are needed.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">nums = [3,2], k = 6</span></p> <p><strong>Output:</strong> <span class="example-io">5</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Perform 3 operations on <code>nums[0] = 3</code> and 2 operations on <code>nums[1] = 2</code>. Now, <code>nums = [0, 0]</code>.</li> <li>The sum is 0, which is divisible by 6.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 1000</code></li> <li><code>1 &lt;= nums[i] &lt;= 1000</code></li> <li><code>1 &lt;= k &lt;= 100</code></li> </ul>
Array; Math
Java
class Solution { public int minOperations(int[] nums, int k) { return Arrays.stream(nums).sum() % k; } }