id
int64
1
3.64k
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,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; } }
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
Python
class Solution: def minOperations(self, nums: List[int], k: int) -> int: return sum(nums) % 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
TypeScript
function minOperations(nums: number[], k: number): number { return nums.reduce((acc, x) => acc + x, 0) % k; }
3,516
Find Closest Person
Easy
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p> <ul data-end="252" data-start="118"> <li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li> <li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li> <li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li> </ul> <p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p> <p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p> <ul data-end="505" data-start="374"> <li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li> <li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li> <li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li> </ul> <p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul data-end="258" data-start="113"> <li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li> <li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li> </ul> <p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, z &lt;= 100</code></li> </ul>
Math
C++
class Solution { public: int findClosest(int x, int y, int z) { int a = abs(x - z); int b = abs(y - z); return a == b ? 0 : (a < b ? 1 : 2); } };
3,516
Find Closest Person
Easy
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p> <ul data-end="252" data-start="118"> <li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li> <li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li> <li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li> </ul> <p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p> <p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p> <ul data-end="505" data-start="374"> <li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li> <li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li> <li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li> </ul> <p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul data-end="258" data-start="113"> <li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li> <li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li> </ul> <p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, z &lt;= 100</code></li> </ul>
Math
Go
func findClosest(x int, y int, z int) int { a, b := abs(x-z), abs(y-z) if a == b { return 0 } if a < b { return 1 } return 2 } func abs(x int) int { if x < 0 { return -x } return x }
3,516
Find Closest Person
Easy
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p> <ul data-end="252" data-start="118"> <li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li> <li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li> <li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li> </ul> <p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p> <p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p> <ul data-end="505" data-start="374"> <li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li> <li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li> <li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li> </ul> <p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul data-end="258" data-start="113"> <li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li> <li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li> </ul> <p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, z &lt;= 100</code></li> </ul>
Math
Java
class Solution { public int findClosest(int x, int y, int z) { int a = Math.abs(x - z); int b = Math.abs(y - z); return a == b ? 0 : (a < b ? 1 : 2); } }
3,516
Find Closest Person
Easy
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p> <ul data-end="252" data-start="118"> <li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li> <li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li> <li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li> </ul> <p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p> <p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p> <ul data-end="505" data-start="374"> <li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li> <li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li> <li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li> </ul> <p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul data-end="258" data-start="113"> <li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li> <li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li> </ul> <p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, z &lt;= 100</code></li> </ul>
Math
Python
class Solution: def findClosest(self, x: int, y: int, z: int) -> int: a = abs(x - z) b = abs(y - z) return 0 if a == b else (1 if a < b else 2)
3,516
Find Closest Person
Easy
<p data-end="116" data-start="0">You are given three integers <code data-end="33" data-start="30">x</code>, <code data-end="38" data-start="35">y</code>, and <code data-end="47" data-start="44">z</code>, representing the positions of three people on a number line:</p> <ul data-end="252" data-start="118"> <li data-end="154" data-start="118"><code data-end="123" data-start="120">x</code> is the position of Person 1.</li> <li data-end="191" data-start="155"><code data-end="160" data-start="157">y</code> is the position of Person 2.</li> <li data-end="252" data-start="192"><code data-end="197" data-start="194">z</code> is the position of Person 3, who does <strong>not</strong> move.</li> </ul> <p data-end="322" data-start="254">Both Person 1 and Person 2 move toward Person 3 at the <strong>same</strong> speed.</p> <p data-end="372" data-start="324">Determine which person reaches Person 3 <strong>first</strong>:</p> <ul data-end="505" data-start="374"> <li data-end="415" data-start="374">Return 1 if Person 1 arrives first.</li> <li data-end="457" data-start="416">Return 2 if Person 2 arrives first.</li> <li data-end="505" data-start="458">Return 0 if both arrive at the <strong>same</strong> time.</li> </ul> <p data-end="537" data-is-last-node="" data-is-only-node="" data-start="507">Return the result accordingly.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 7, z = 4</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <ul data-end="258" data-start="113"> <li data-end="193" data-start="113">Person 1 is at position 2 and can reach Person 3 (at position 4) in 2 steps.</li> <li data-end="258" data-start="194">Person 2 is at position 7 and can reach Person 3 in 3 steps.</li> </ul> <p data-end="317" data-is-last-node="" data-is-only-node="" data-start="260">Since Person 1 reaches Person 3 first, the output is 1.</p> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 2, y = 5, z = 6</span></p> <p><strong>Output:</strong> <span class="example-io">2</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 2 and can reach Person 3 (at position 6) in 4 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 1 step.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since Person 2 reaches Person 3 first, the output is 2.</p> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">x = 1, y = 5, z = 3</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <ul data-end="245" data-start="92"> <li data-end="174" data-start="92">Person 1 is at position 1 and can reach Person 3 (at position 3) in 2 steps.</li> <li data-end="245" data-start="175">Person 2 is at position 5 and can reach Person 3 in 2 steps.</li> </ul> <p data-end="304" data-is-last-node="" data-is-only-node="" data-start="247">Since both Person 1 and Person 2 reach Person 3 at the same time, the output is 0.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= x, y, z &lt;= 100</code></li> </ul>
Math
TypeScript
function findClosest(x: number, y: number, z: number): number { const a = Math.abs(x - z); const b = Math.abs(y - z); return a === b ? 0 : a < b ? 1 : 2; }
3,522
Calculate Score After Performing Instructions
Medium
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p> <p>You need to simulate a process based on the following rules:</p> <ul> <li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li> <li>If <code>instructions[i]</code> is <code>&quot;add&quot;</code>: <ul> <li>Add <code>values[i]</code> to your score.</li> <li>Move to the next instruction <code>(i + 1)</code>.</li> </ul> </li> <li>If <code>instructions[i]</code> is <code>&quot;jump&quot;</code>: <ul> <li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li> </ul> </li> </ul> <p>The process ends when you either:</p> <ul> <li>Go out of bounds (i.e., <code>i &lt; 0 or i &gt;= n</code>), or</li> <li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li> </ul> <p>Return your score at the end of the process.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;,&quot;jump&quot;,&quot;add&quot;,&quot;jump&quot;], values = [2,1,3,1,-2,-3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 2 = 2</code>.</li> <li>At index 2: Instruction is <code>&quot;add&quot;</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li> <li>At index 3: Instruction is <code>&quot;jump&quot;</code>, move to index <code>3 + 1 = 4</code>.</li> <li>At index 4: Instruction is <code>&quot;add&quot;</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li> <li>At index 5: Instruction is <code>&quot;jump&quot;</code>, move to index <code>5 + (-3) = 2</code>.</li> <li>At index 2: Already visited. The process ends.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;], values = [3,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 3 = 3</code>.</li> <li>At index 3: Out of bounds. The process ends.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;], values = [0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 0 = 0</code>.</li> <li>At index 0: Already visited. The process ends.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == instructions.length == values.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>instructions[i]</code> is either <code>&quot;add&quot;</code> or <code>&quot;jump&quot;</code>.</li> <li><code>-10<sup>5</sup> &lt;= values[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; String; Simulation
C++
class Solution { public: long long calculateScore(vector<string>& instructions, vector<int>& values) { int n = values.size(); vector<bool> vis(n, false); long long ans = 0; int i = 0; while (i >= 0 && i < n && !vis[i]) { vis[i] = true; if (instructions[i][0] == 'a') { ans += values[i]; i += 1; } else { i += values[i]; } } return ans; } };
3,522
Calculate Score After Performing Instructions
Medium
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p> <p>You need to simulate a process based on the following rules:</p> <ul> <li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li> <li>If <code>instructions[i]</code> is <code>&quot;add&quot;</code>: <ul> <li>Add <code>values[i]</code> to your score.</li> <li>Move to the next instruction <code>(i + 1)</code>.</li> </ul> </li> <li>If <code>instructions[i]</code> is <code>&quot;jump&quot;</code>: <ul> <li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li> </ul> </li> </ul> <p>The process ends when you either:</p> <ul> <li>Go out of bounds (i.e., <code>i &lt; 0 or i &gt;= n</code>), or</li> <li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li> </ul> <p>Return your score at the end of the process.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;,&quot;jump&quot;,&quot;add&quot;,&quot;jump&quot;], values = [2,1,3,1,-2,-3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 2 = 2</code>.</li> <li>At index 2: Instruction is <code>&quot;add&quot;</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li> <li>At index 3: Instruction is <code>&quot;jump&quot;</code>, move to index <code>3 + 1 = 4</code>.</li> <li>At index 4: Instruction is <code>&quot;add&quot;</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li> <li>At index 5: Instruction is <code>&quot;jump&quot;</code>, move to index <code>5 + (-3) = 2</code>.</li> <li>At index 2: Already visited. The process ends.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;], values = [3,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 3 = 3</code>.</li> <li>At index 3: Out of bounds. The process ends.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;], values = [0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 0 = 0</code>.</li> <li>At index 0: Already visited. The process ends.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == instructions.length == values.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>instructions[i]</code> is either <code>&quot;add&quot;</code> or <code>&quot;jump&quot;</code>.</li> <li><code>-10<sup>5</sup> &lt;= values[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; String; Simulation
Go
func calculateScore(instructions []string, values []int) (ans int64) { n := len(values) vis := make([]bool, n) i := 0 for i >= 0 && i < n && !vis[i] { vis[i] = true if instructions[i][0] == 'a' { ans += int64(values[i]) i += 1 } else { i += values[i] } } return }
3,522
Calculate Score After Performing Instructions
Medium
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p> <p>You need to simulate a process based on the following rules:</p> <ul> <li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li> <li>If <code>instructions[i]</code> is <code>&quot;add&quot;</code>: <ul> <li>Add <code>values[i]</code> to your score.</li> <li>Move to the next instruction <code>(i + 1)</code>.</li> </ul> </li> <li>If <code>instructions[i]</code> is <code>&quot;jump&quot;</code>: <ul> <li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li> </ul> </li> </ul> <p>The process ends when you either:</p> <ul> <li>Go out of bounds (i.e., <code>i &lt; 0 or i &gt;= n</code>), or</li> <li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li> </ul> <p>Return your score at the end of the process.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;,&quot;jump&quot;,&quot;add&quot;,&quot;jump&quot;], values = [2,1,3,1,-2,-3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 2 = 2</code>.</li> <li>At index 2: Instruction is <code>&quot;add&quot;</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li> <li>At index 3: Instruction is <code>&quot;jump&quot;</code>, move to index <code>3 + 1 = 4</code>.</li> <li>At index 4: Instruction is <code>&quot;add&quot;</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li> <li>At index 5: Instruction is <code>&quot;jump&quot;</code>, move to index <code>5 + (-3) = 2</code>.</li> <li>At index 2: Already visited. The process ends.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;], values = [3,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 3 = 3</code>.</li> <li>At index 3: Out of bounds. The process ends.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;], values = [0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 0 = 0</code>.</li> <li>At index 0: Already visited. The process ends.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == instructions.length == values.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>instructions[i]</code> is either <code>&quot;add&quot;</code> or <code>&quot;jump&quot;</code>.</li> <li><code>-10<sup>5</sup> &lt;= values[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; String; Simulation
Java
class Solution { public long calculateScore(String[] instructions, int[] values) { int n = values.length; boolean[] vis = new boolean[n]; long ans = 0; int i = 0; while (i >= 0 && i < n && !vis[i]) { vis[i] = true; if (instructions[i].charAt(0) == 'a') { ans += values[i]; i += 1; } else { i = i + values[i]; } } return ans; } }
3,522
Calculate Score After Performing Instructions
Medium
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p> <p>You need to simulate a process based on the following rules:</p> <ul> <li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li> <li>If <code>instructions[i]</code> is <code>&quot;add&quot;</code>: <ul> <li>Add <code>values[i]</code> to your score.</li> <li>Move to the next instruction <code>(i + 1)</code>.</li> </ul> </li> <li>If <code>instructions[i]</code> is <code>&quot;jump&quot;</code>: <ul> <li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li> </ul> </li> </ul> <p>The process ends when you either:</p> <ul> <li>Go out of bounds (i.e., <code>i &lt; 0 or i &gt;= n</code>), or</li> <li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li> </ul> <p>Return your score at the end of the process.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;,&quot;jump&quot;,&quot;add&quot;,&quot;jump&quot;], values = [2,1,3,1,-2,-3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 2 = 2</code>.</li> <li>At index 2: Instruction is <code>&quot;add&quot;</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li> <li>At index 3: Instruction is <code>&quot;jump&quot;</code>, move to index <code>3 + 1 = 4</code>.</li> <li>At index 4: Instruction is <code>&quot;add&quot;</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li> <li>At index 5: Instruction is <code>&quot;jump&quot;</code>, move to index <code>5 + (-3) = 2</code>.</li> <li>At index 2: Already visited. The process ends.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;], values = [3,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 3 = 3</code>.</li> <li>At index 3: Out of bounds. The process ends.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;], values = [0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 0 = 0</code>.</li> <li>At index 0: Already visited. The process ends.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == instructions.length == values.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>instructions[i]</code> is either <code>&quot;add&quot;</code> or <code>&quot;jump&quot;</code>.</li> <li><code>-10<sup>5</sup> &lt;= values[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; String; Simulation
Python
class Solution: def calculateScore(self, instructions: List[str], values: List[int]) -> int: n = len(values) vis = [False] * n ans = i = 0 while 0 <= i < n and not vis[i]: vis[i] = True if instructions[i][0] == "a": ans += values[i] i += 1 else: i = i + values[i] return ans
3,522
Calculate Score After Performing Instructions
Medium
<p>You are given two arrays, <code>instructions</code> and <code>values</code>, both of size <code>n</code>.</p> <p>You need to simulate a process based on the following rules:</p> <ul> <li>You start at the first instruction at index <code>i = 0</code> with an initial score of 0.</li> <li>If <code>instructions[i]</code> is <code>&quot;add&quot;</code>: <ul> <li>Add <code>values[i]</code> to your score.</li> <li>Move to the next instruction <code>(i + 1)</code>.</li> </ul> </li> <li>If <code>instructions[i]</code> is <code>&quot;jump&quot;</code>: <ul> <li>Move to the instruction at index <code>(i + values[i])</code> without modifying your score.</li> </ul> </li> </ul> <p>The process ends when you either:</p> <ul> <li>Go out of bounds (i.e., <code>i &lt; 0 or i &gt;= n</code>), or</li> <li>Attempt to revisit an instruction that has been previously executed. The revisited instruction is not executed.</li> </ul> <p>Return your score at the end of the process.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;,&quot;jump&quot;,&quot;add&quot;,&quot;jump&quot;], values = [2,1,3,1,-2,-3]</span></p> <p><strong>Output:</strong> <span class="example-io">1</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 2 = 2</code>.</li> <li>At index 2: Instruction is <code>&quot;add&quot;</code>, add <code>values[2] = 3</code> to your score and move to index 3. Your score becomes 3.</li> <li>At index 3: Instruction is <code>&quot;jump&quot;</code>, move to index <code>3 + 1 = 4</code>.</li> <li>At index 4: Instruction is <code>&quot;add&quot;</code>, add <code>values[4] = -2</code> to your score and move to index 5. Your score becomes 1.</li> <li>At index 5: Instruction is <code>&quot;jump&quot;</code>, move to index <code>5 + (-3) = 2</code>.</li> <li>At index 2: Already visited. The process ends.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;,&quot;add&quot;,&quot;add&quot;], values = [3,1,1]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 3 = 3</code>.</li> <li>At index 3: Out of bounds. The process ends.</li> </ul> </div> <p><strong class="example">Example 3:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">instructions = [&quot;jump&quot;], values = [0]</span></p> <p><strong>Output:</strong> <span class="example-io">0</span></p> <p><strong>Explanation:</strong></p> <p>Simulate the process starting at instruction 0:</p> <ul> <li>At index 0: Instruction is <code>&quot;jump&quot;</code>, move to index <code>0 + 0 = 0</code>.</li> <li>At index 0: Already visited. The process ends.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>n == instructions.length == values.length</code></li> <li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li> <li><code>instructions[i]</code> is either <code>&quot;add&quot;</code> or <code>&quot;jump&quot;</code>.</li> <li><code>-10<sup>5</sup> &lt;= values[i] &lt;= 10<sup>5</sup></code></li> </ul>
Array; Hash Table; String; Simulation
TypeScript
function calculateScore(instructions: string[], values: number[]): number { const n = values.length; const vis: boolean[] = Array(n).fill(false); let ans = 0; let i = 0; while (i >= 0 && i < n && !vis[i]) { vis[i] = true; if (instructions[i][0] === 'a') { ans += values[i]; i += 1; } else { i += values[i]; } } return ans; }
3,523
Make Array Non-decreasing
Medium
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p> <p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</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 = [4,2,5,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way to achieve the maximum size is:</p> <ol> <li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 3, 5]</code>.</li> <li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 5]</code>.</li> </ol> <p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></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]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
C++
class Solution { public: int maximumPossibleSize(vector<int>& nums) { int ans = 0, mx = 0; for (int x : nums) { if (mx <= x) { ++ans; mx = x; } } return ans; } };
3,523
Make Array Non-decreasing
Medium
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p> <p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</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 = [4,2,5,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way to achieve the maximum size is:</p> <ol> <li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 3, 5]</code>.</li> <li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 5]</code>.</li> </ol> <p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></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]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
Go
func maximumPossibleSize(nums []int) int { ans, mx := 0, 0 for _, x := range nums { if mx <= x { ans++ mx = x } } return ans }
3,523
Make Array Non-decreasing
Medium
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p> <p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</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 = [4,2,5,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way to achieve the maximum size is:</p> <ol> <li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 3, 5]</code>.</li> <li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 5]</code>.</li> </ol> <p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></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]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
Java
class Solution { public int maximumPossibleSize(int[] nums) { int ans = 0, mx = 0; for (int x : nums) { if (mx <= x) { ++ans; mx = x; } } return ans; } }
3,523
Make Array Non-decreasing
Medium
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p> <p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</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 = [4,2,5,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way to achieve the maximum size is:</p> <ol> <li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 3, 5]</code>.</li> <li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 5]</code>.</li> </ol> <p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></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]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
Python
class Solution: def maximumPossibleSize(self, nums: List[int]) -> int: ans = mx = 0 for x in nums: if mx <= x: ans += 1 mx = x return ans
3,523
Make Array Non-decreasing
Medium
<p>You are given an integer array <code>nums</code>. In one operation, you can select a <span data-keyword="subarray-nonempty">subarray</span> and replace it with a single element equal to its <strong>maximum</strong> value.</p> <p>Return the <strong>maximum possible size</strong> of the array after performing zero or more operations such that the resulting array is <strong>non-decreasing</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 = [4,2,5,3,5]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>One way to achieve the maximum size is:</p> <ol> <li>Replace subarray <code>nums[1..2] = [2, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 3, 5]</code>.</li> <li>Replace subarray <code>nums[2..3] = [3, 5]</code> with <code>5</code> &rarr; <code>[4, 5, 5]</code>.</li> </ol> <p>The final array <code>[4, 5, 5]</code> is non-decreasing with size <font face="monospace">3.</font></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]</span></p> <p><strong>Output:</strong> <span class="example-io">3</span></p> <p><strong>Explanation:</strong></p> <p>No operation is needed as the array <code>[1,2,3]</code> is already non-decreasing.</p> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li> <li><code>1 &lt;= nums[i] &lt;= 2 * 10<sup>5</sup></code></li> </ul>
Stack; Greedy; Array; Monotonic Stack
TypeScript
function maximumPossibleSize(nums: number[]): number { let [ans, mx] = [0, 0]; for (const x of nums) { if (mx <= x) { ++ans; mx = x; } } return ans; }
3,527
Find the Most Common Response
Medium
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p> <p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;,&quot;ok&quot;],[&quot;ok&quot;,&quot;bad&quot;,&quot;good&quot;,&quot;ok&quot;,&quot;ok&quot;],[&quot;good&quot;],[&quot;bad&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;good&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list, <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;, &quot;good&quot;], [&quot;good&quot;], [&quot;bad&quot;]]</code>.</li> <li><code>&quot;good&quot;</code> appears 3 times, <code>&quot;ok&quot;</code> appears 2 times, and <code>&quot;bad&quot;</code> appears 2 times.</li> <li>Return <code>&quot;good&quot;</code> because it has the highest frequency.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;],[&quot;ok&quot;,&quot;bad&quot;],[&quot;bad&quot;,&quot;notsure&quot;],[&quot;great&quot;,&quot;good&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bad&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list we have <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;], [&quot;bad&quot;, &quot;notsure&quot;], [&quot;great&quot;, &quot;good&quot;]]</code>.</li> <li><code>&quot;bad&quot;</code>, <code>&quot;good&quot;</code>, and <code>&quot;ok&quot;</code> each occur 2 times.</li> <li>The output is <code>&quot;bad&quot;</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= responses.length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i].length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i][j].length &lt;= 10</code></li> <li><code>responses[i][j]</code> consists of only lowercase English letters</li> </ul>
Array; Hash Table; String; Counting
C++
class Solution { public: string findCommonResponse(vector<vector<string>>& responses) { unordered_map<string, int> cnt; for (const auto& ws : responses) { unordered_set<string> s; for (const auto& w : ws) { if (s.insert(w).second) { ++cnt[w]; } } } string ans = responses[0][0]; for (const auto& e : cnt) { const string& w = e.first; int v = e.second; if (cnt[ans] < v || (cnt[ans] == v && w < ans)) { ans = w; } } return ans; } };
3,527
Find the Most Common Response
Medium
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p> <p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;,&quot;ok&quot;],[&quot;ok&quot;,&quot;bad&quot;,&quot;good&quot;,&quot;ok&quot;,&quot;ok&quot;],[&quot;good&quot;],[&quot;bad&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;good&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list, <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;, &quot;good&quot;], [&quot;good&quot;], [&quot;bad&quot;]]</code>.</li> <li><code>&quot;good&quot;</code> appears 3 times, <code>&quot;ok&quot;</code> appears 2 times, and <code>&quot;bad&quot;</code> appears 2 times.</li> <li>Return <code>&quot;good&quot;</code> because it has the highest frequency.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;],[&quot;ok&quot;,&quot;bad&quot;],[&quot;bad&quot;,&quot;notsure&quot;],[&quot;great&quot;,&quot;good&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bad&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list we have <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;], [&quot;bad&quot;, &quot;notsure&quot;], [&quot;great&quot;, &quot;good&quot;]]</code>.</li> <li><code>&quot;bad&quot;</code>, <code>&quot;good&quot;</code>, and <code>&quot;ok&quot;</code> each occur 2 times.</li> <li>The output is <code>&quot;bad&quot;</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= responses.length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i].length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i][j].length &lt;= 10</code></li> <li><code>responses[i][j]</code> consists of only lowercase English letters</li> </ul>
Array; Hash Table; String; Counting
Go
func findCommonResponse(responses [][]string) string { cnt := map[string]int{} for _, ws := range responses { s := map[string]struct{}{} for _, w := range ws { if _, ok := s[w]; !ok { s[w] = struct{}{} cnt[w]++ } } } ans := responses[0][0] for w, v := range cnt { if cnt[ans] < v || (cnt[ans] == v && w < ans) { ans = w } } return ans }
3,527
Find the Most Common Response
Medium
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p> <p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;,&quot;ok&quot;],[&quot;ok&quot;,&quot;bad&quot;,&quot;good&quot;,&quot;ok&quot;,&quot;ok&quot;],[&quot;good&quot;],[&quot;bad&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;good&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list, <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;, &quot;good&quot;], [&quot;good&quot;], [&quot;bad&quot;]]</code>.</li> <li><code>&quot;good&quot;</code> appears 3 times, <code>&quot;ok&quot;</code> appears 2 times, and <code>&quot;bad&quot;</code> appears 2 times.</li> <li>Return <code>&quot;good&quot;</code> because it has the highest frequency.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;],[&quot;ok&quot;,&quot;bad&quot;],[&quot;bad&quot;,&quot;notsure&quot;],[&quot;great&quot;,&quot;good&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bad&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list we have <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;], [&quot;bad&quot;, &quot;notsure&quot;], [&quot;great&quot;, &quot;good&quot;]]</code>.</li> <li><code>&quot;bad&quot;</code>, <code>&quot;good&quot;</code>, and <code>&quot;ok&quot;</code> each occur 2 times.</li> <li>The output is <code>&quot;bad&quot;</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= responses.length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i].length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i][j].length &lt;= 10</code></li> <li><code>responses[i][j]</code> consists of only lowercase English letters</li> </ul>
Array; Hash Table; String; Counting
Java
class Solution { public String findCommonResponse(List<List<String>> responses) { Map<String, Integer> cnt = new HashMap<>(); for (var ws : responses) { Set<String> s = new HashSet<>(); for (var w : ws) { if (s.add(w)) { cnt.merge(w, 1, Integer::sum); } } } String ans = responses.get(0).get(0); for (var e : cnt.entrySet()) { String w = e.getKey(); int v = e.getValue(); if (cnt.get(ans) < v || (cnt.get(ans) == v && w.compareTo(ans) < 0)) { ans = w; } } return ans; } }
3,527
Find the Most Common Response
Medium
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p> <p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;,&quot;ok&quot;],[&quot;ok&quot;,&quot;bad&quot;,&quot;good&quot;,&quot;ok&quot;,&quot;ok&quot;],[&quot;good&quot;],[&quot;bad&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;good&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list, <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;, &quot;good&quot;], [&quot;good&quot;], [&quot;bad&quot;]]</code>.</li> <li><code>&quot;good&quot;</code> appears 3 times, <code>&quot;ok&quot;</code> appears 2 times, and <code>&quot;bad&quot;</code> appears 2 times.</li> <li>Return <code>&quot;good&quot;</code> because it has the highest frequency.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;],[&quot;ok&quot;,&quot;bad&quot;],[&quot;bad&quot;,&quot;notsure&quot;],[&quot;great&quot;,&quot;good&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bad&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list we have <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;], [&quot;bad&quot;, &quot;notsure&quot;], [&quot;great&quot;, &quot;good&quot;]]</code>.</li> <li><code>&quot;bad&quot;</code>, <code>&quot;good&quot;</code>, and <code>&quot;ok&quot;</code> each occur 2 times.</li> <li>The output is <code>&quot;bad&quot;</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= responses.length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i].length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i][j].length &lt;= 10</code></li> <li><code>responses[i][j]</code> consists of only lowercase English letters</li> </ul>
Array; Hash Table; String; Counting
Python
class Solution: def findCommonResponse(self, responses: List[List[str]]) -> str: cnt = Counter() for ws in responses: for w in set(ws): cnt[w] += 1 ans = responses[0][0] for w, x in cnt.items(): if cnt[ans] < x or (cnt[ans] == x and w < ans): ans = w return ans
3,527
Find the Most Common Response
Medium
<p>You are given a 2D string array <code>responses</code> where each <code>responses[i]</code> is an array of strings representing survey responses from the <code>i<sup>th</sup></code> day.</p> <p>Return the <strong>most common</strong> response across all days after removing <strong>duplicate</strong> responses within each <code>responses[i]</code>. If there is a tie, return the <em><span data-keyword="lexicographically-smaller-string">lexicographically smallest</span></em> response.</p> <p>&nbsp;</p> <p><strong class="example">Example 1:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;,&quot;ok&quot;],[&quot;ok&quot;,&quot;bad&quot;,&quot;good&quot;,&quot;ok&quot;,&quot;ok&quot;],[&quot;good&quot;],[&quot;bad&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;good&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list, <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;, &quot;good&quot;], [&quot;good&quot;], [&quot;bad&quot;]]</code>.</li> <li><code>&quot;good&quot;</code> appears 3 times, <code>&quot;ok&quot;</code> appears 2 times, and <code>&quot;bad&quot;</code> appears 2 times.</li> <li>Return <code>&quot;good&quot;</code> because it has the highest frequency.</li> </ul> </div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">responses = [[&quot;good&quot;,&quot;ok&quot;,&quot;good&quot;],[&quot;ok&quot;,&quot;bad&quot;],[&quot;bad&quot;,&quot;notsure&quot;],[&quot;great&quot;,&quot;good&quot;]]</span></p> <p><strong>Output:</strong> <span class="example-io">&quot;bad&quot;</span></p> <p><strong>Explanation:</strong></p> <ul> <li>After removing duplicates within each list we have <code>responses = [[&quot;good&quot;, &quot;ok&quot;], [&quot;ok&quot;, &quot;bad&quot;], [&quot;bad&quot;, &quot;notsure&quot;], [&quot;great&quot;, &quot;good&quot;]]</code>.</li> <li><code>&quot;bad&quot;</code>, <code>&quot;good&quot;</code>, and <code>&quot;ok&quot;</code> each occur 2 times.</li> <li>The output is <code>&quot;bad&quot;</code> because it is the lexicographically smallest amongst the words with the highest frequency.</li> </ul> </div> <p>&nbsp;</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 &lt;= responses.length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i].length &lt;= 1000</code></li> <li><code>1 &lt;= responses[i][j].length &lt;= 10</code></li> <li><code>responses[i][j]</code> consists of only lowercase English letters</li> </ul>
Array; Hash Table; String; Counting
TypeScript
function findCommonResponse(responses: string[][]): string { const cnt = new Map<string, number>(); for (const ws of responses) { const s = new Set<string>(); for (const w of ws) { if (!s.has(w)) { s.add(w); cnt.set(w, (cnt.get(w) ?? 0) + 1); } } } let ans = responses[0][0]; for (const [w, v] of cnt) { const best = cnt.get(ans)!; if (best < v || (best === v && w < ans)) { ans = w; } } return ans; }
3,528
Unit Conversion I
Medium
<p>There are <code>n</code> types of units indexed from <code>0</code> to <code>n - 1</code>. You are given a 2D integer array <code>conversions</code> of length <code>n - 1</code>, where <code>conversions[i] = [sourceUnit<sub>i</sub>, targetUnit<sub>i</sub>, conversionFactor<sub>i</sub>]</code>. This indicates that a single unit of type <code>sourceUnit<sub>i</sub></code> is equivalent to <code>conversionFactor<sub>i</sub></code> units of type <code>targetUnit<sub>i</sub></code>.</p> <p>Return an array <code>baseUnitConversion</code> of length <code>n</code>, where <code>baseUnitConversion[i]</code> is the number of units of type <code>i</code> equivalent to a single unit of type 0. Since the answer may be large, return each <code>baseUnitConversion[i]</code> <strong>modulo</strong> <code>10<sup>9</sup> + 7</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">conversions = [[0,1,2],[1,2,3]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,6]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 2 using <code>conversions[0]</code>, then <code>conversions[1]</code>.</li> </ul> <img alt="" src="https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/3500-3599/3528.Unit%20Conversion%20I/images/example1.png" style="width: 545px; height: 118px;" /></div> <p><strong class="example">Example 2:</strong></p> <div class="example-block"> <p><strong>Input:</strong> <span class="example-io">conversions = [[0,1,2],[0,2,3],[1,3,4],[1,4,5],[2,5,2],[4,6,3],[5,7,4]]</span></p> <p><strong>Output:</strong> <span class="example-io">[1,2,3,8,10,6,30,24]</span></p> <p><strong>Explanation:</strong></p> <ul> <li>Convert a single unit of type 0 into 2 units of type 1 using <code>conversions[0]</code>.</li> <li>Convert a single unit of type 0 into 3 units of type 2 using <code>conversions[1]</code>.</li> <li>Convert a single unit of type 0 into 8 units of type 3 using <code>conversions[0]</code>, then <code>conversions[2]</code>.</li> <li>Convert a single unit of type 0 into 10 units of type 4 using <code>conversions[0]</code>, then <code>conversions[3]</code>.</li> <li>Convert a single unit of type 0 into 6 units of type 5 using <code>conversions[1]</code>, then <code>conversions[4]</code>.</li> <li>Convert a single unit of type 0 into 30 units of type 6 using <code>conversions[0]</code>, <code>conversions[3]</code>, then <code>conversions[5]</code>.</li> <li>Convert a single unit of type 0 into 24 units of type 7 using <code>conversions[1]</code>, <code>conversions[4]</code>, then <code>conversions[6]</code>.</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>conversions.length == n - 1</code></li> <li><code>0 &lt;= sourceUnit<sub>i</sub>, targetUnit<sub>i</sub> &lt; n</code></li> <li><code>1 &lt;= conversionFactor<sub>i</sub> &lt;= 10<sup>9</sup></code></li> <li>It is guaranteed that unit 0 can be converted into any other unit through a <strong>unique</strong> combination of conversions without using any conversions in the opposite direction.</li> </ul>
Depth-First Search; Breadth-First Search; Graph
C++
class Solution { public: vector<int> baseUnitConversions(vector<vector<int>>& conversions) { const int mod = 1e9 + 7; int n = conversions.size() + 1; vector<vector<pair<int, int>>> g(n); vector<int> ans(n); for (const auto& e : conversions) { g[e[0]].push_back({e[1], e[2]}); } auto dfs = [&](this auto&& dfs, int s, long long mul) -> void { ans[s] = mul; for (auto [t, w] : g[s]) { dfs(t, mul * w % mod); } }; dfs(0, 1); return ans; } };