A software development company is creating several shared computing systems throughout an office. Each network requires:
- All computers must be adjacent to one another.
- Each network has a minimum number of computers (
minComps). - Total processing speed of computers in a network (sum of
speed) must be at leastspeedThreshold. - A computer can only belong to one network.
Given speed[n] (order represents adjacency on a line) and minComps, speedThreshold, return the maximum number of networks.
解法
从左到右贪心:扩展当前段直到长度和总和约束都满足,然后封段重开。复杂度 O(N)。
def solve(speed, min_comps, threshold):
nets = length = total = 0
for s in speed:
length += 1; total += s
if length >= min_comps and total >= threshold:
nets += 1; length = total = 0
return netsclass Solution {
public int solve(int[] speed, int minComps, int threshold) {
int nets = 0, len = 0;
long sum = 0;
for (int s : speed) {
len++; sum += s;
if (len >= minComps && sum >= threshold) { nets++; len = 0; sum = 0; }
}
return nets;
}
}int solve(vector<int>& speed, int minComps, int threshold) {
int nets = 0, len = 0;
long long sum = 0;
for (int s : speed) {
++len; sum += s;
if (len >= minComps && sum >= threshold) { ++nets; len = 0; sum = 0; }
}
return nets;
}Given an integer array a, partition it into two disjoint non-empty contiguous subarrays. Return the maximum sum of (max subarray sum of part 1) + (max subarray sum of part 2).
Example: a = [-1, 4, -2, 5, -3, 6] → split after index 1 gives [(-1, 4)] with best 4 and [-2, 5, -3, 6] with best 8; answer 4 + 8 = 12. Try every split point and take the max.
解法
两遍 Kadane:L[i] 为 a[0..i] 内最大子数组和,R[i] 为 a[i..n-1] 内最大子数组和。答案 = max(L[i] + R[i+1])。复杂度 O(N)。
def solve(a):
n = len(a)
L = [0] * n; R = [0] * n
cur = best = a[0]; L[0] = best
for i in range(1, n):
cur = max(a[i], cur + a[i]); best = max(best, cur); L[i] = best
cur = best = a[-1]; R[-1] = best
for i in range(n - 2, -1, -1):
cur = max(a[i], cur + a[i]); best = max(best, cur); R[i] = best
return max(L[i] + R[i + 1] for i in range(n - 1))class Solution {
public long solve(int[] a) {
int n = a.length;
long[] L = new long[n], R = new long[n];
long cur = 0, best = Long.MIN_VALUE;
for (int i = 0; i < n; i++) {
cur = Math.max(a[i], cur + a[i]);
best = Math.max(best, cur);
L[i] = best;
}
cur = 0; best = Long.MIN_VALUE;
for (int i = n - 1; i >= 0; i--) {
cur = Math.max(a[i], cur + a[i]);
best = Math.max(best, cur);
R[i] = best;
}
long ans = Long.MIN_VALUE;
for (int i = 0; i + 1 < n; i++) ans = Math.max(ans, L[i] + R[i + 1]);
return ans;
}
}long long solve(vector<int>& a) {
int n = a.size();
vector<long long> L(n, 0), R(n, 0);
long long cur = 0, best = LLONG_MIN;
for (int i = 0; i < n; ++i) {
cur = max((long long)a[i], cur + a[i]);
best = max(best, cur);
L[i] = best;
}
cur = 0; best = LLONG_MIN;
for (int i = n - 1; i >= 0; --i) {
cur = max((long long)a[i], cur + a[i]);
best = max(best, cur);
R[i] = best;
}
long long ans = LLONG_MIN;
for (int i = 0; i + 1 < n; ++i) ans = max(ans, L[i] + R[i + 1]);
return ans;
}There are n planned updates. Update i can be released on plannedDate[i] or its earlier alternateDate[i]. Updates must be released in the order of their planned release date, but multiple updates can release the same day. Return the minimum total days to release all updates.
解法
按 plannedDate 排序,遍历每次更新:备用日期 ≥ 当前日则用备用日期,否则回退到 plannedDate。复杂度 O(N log N)。
def solve(planned, alternate):
day = 0
for p, a in sorted(zip(planned, alternate)):
day = max(day, a if a >= day else p)
return dayclass Solution {
public int solve(int[] planned, int[] alternate) {
int n = planned.length;
int[][] v = new int[n][2];
for (int i = 0; i < n; i++) { v[i][0] = planned[i]; v[i][1] = alternate[i]; }
Arrays.sort(v, (x, y) -> x[0] - y[0]);
int day = 0;
for (int[] x : v) day = Math.max(day, x[1] >= day ? x[1] : x[0]);
return day;
}
}int solve(vector<int>& planned, vector<int>& alternate) {
int n = planned.size();
vector<pair<int,int>> v;
for (int i = 0; i < n; ++i) v.push_back({planned[i], alternate[i]});
sort(v.begin(), v.end());
int day = 0;
for (auto& [p, a] : v) day = max(day, a >= day ? a : p);
return day;
}04Star Sum
Given an undirected weighted graph G with g_nodes nodes and edges, where node i has value values[i]. A k-star = a star subgraph with one center and at most k arms (leaves are direct neighbors of center). Return the largest sum of values over all k-stars (sum = center value + sum of selected leaf values).
Example: n = 5, edges = [[0,1],[0,2],[1,3],[1,4]], values = [3, 4, -1, 2, 5], k = 2 → center 1 with leaves {4 (val 5), 3 (val 2)} gives 4 + 5 + 2 = 11. Best across all centers.
Given a binary string s, segregate by moving all 1s to the right end. A single operation: choose any 1 and move it right until hitting 0-end or another 1. Cost = 1 + (places moved). Move a 1 to its rightmost possible position is mandatory each op. Find the maximum total cost to fully segregate.
A Tick describes a range with [lowerBound, upperBound) and a width. A VariableTickTable has cabinetPrice and a vector of Tick ranges. For each input price:
- If
price == cabinetPrice→ no rounding needed. - Else if
priceis already tick-aligned in its range → unchanged. - Else round to nearest multiple of the range's width (ties → up).
Example: cabinet = 0.01, ticks [(0, 1, 0.01), (1, 5, 0.05), (5, 100, 0.10)], prices [0.01, 0.4, 1.07] → [0.01, 0.4, 1.05] (1.07 in range [1,5) rounds to nearest 0.05 step = 1.05).
Maintain a limit-order book against a market-maker reference. The displayable best bid/ask is computed from non-MM orders that (1) have a quantity divisible by lot_size, and (2) either improve the MM price or match it with quantity strictly greater than 5% of MM size. Support add(orderId, ts, isBid, price, qty) and cancel(orderId, ts), each returning the current displayed (best_bid, best_ask), clamped to MM as fallback.
Log throttle = each "publication" of bytesUtil bytes is allowed only if the rolling-window sum within last window seconds (inclusive) stays ≤ bytesUtil bytes.
For each new log of size bytes at time timestamp, decide if it can be published. Return the indices of successfully published logs.
For each index i of arr, set a counter to 0 and walk every left neighbor j < i: if arr[j] > arr[i] subtract |arr[j] - arr[i]| from the counter, otherwise add |arr[j] - arr[i]|. Return the resulting counter array.
Example: arr = [2, 4, 3] → [0, 2, 0]. For i = 2: vs arr[1] = 4 subtract 1 (counter = -1), vs arr[0] = 2 add 1 (counter = 0).
| # | Sequence | Answer | Rule |
|---|---|---|---|
| 2 | 5, 8, 13, 21, 34, __ | 55 | Fibonacci |
| 3 | 4, 16, 52, 160, 484, __ | 1456 | a*3 + 4 |
| 5 | 1, 2, 4, 7, 11, 16, __ | 22 | diff 1,2,3,4,5,6 |
| 10 | 2, -4, 10, -24, 58, -140, __ | 338 | a[n] = -2*a[n-1] + 2 |
| 12 | F, S, T, F, F, S, __ | S | First/Second/Third/Fourth/Fifth/Sixth/Seventh |
| 13 | 4, 9, 24, 69, 204, __ | 609 | a[n] = a[n-1]*3 - 3 |
| 15 | 84, 60, 48, 42, __ | 39 | diff 24,12,6,3 |
| 17 | 6, 24, 60, 120, 210, __ | 336 | n(n+1)(n+2) |
| 19 | 26, -17, 6, 5, -2, 3, 2, 1, __ | 1 | Fibonacci-like |
For each event, compute its probability p and the corresponding bet payout round(1000 * p / (1 - p)) (Kelly-style fair odds for a 1000-unit stake).
def bet(p: float) -> int:
return round(1000 * p / (1 - p))
| # | Question | Probability | Bet |
|---|---|---|---|
| 1 | Draw one card, face card (J,Q,K) | 12/52 | 300 |
| 2 | 20 marbles (11G/9B), draw 1 green | 11/20 | 1222 |
| 3 | Random hour in day, hour [9, 17) | 8/24 | 500 |
| 4 | Flip 2 coins, HH | 1/4 | 333 |
| 5 | Roll 6-sided die, NOT a 6 | 5/6 | 5000 |
| 6 | Spinner 1–10 twice, sum = 15 | 6/100 | 64 |
| 7 | Flip 4 coins, at least one head | 15/16 | 15000 |
| 8 | Flip 2 coins, at least one head | 3/4 | 3000 |
| 9 | Random 4-digit number, last two = 00 | 1/100 | 10 |
| 10 | Roll 2 dice, sum = 12 | 1/36 | 29 |
| 11 | Wheel 9 sections, lands on 1–5 | 5/9 | 1250 |
| 12 | Random day in Feb 2025, weekday | 20/28 | 2500 |
| 13 | Random int 1–20, prime | 8/20 | 667 |
| 14 | Roll fair die, odd | 1/2 | 1000 |
| 15 | Single card, Ace | 4/52 | 83 |
| 16 | Flip 2 coins, sequence HT | 1/4 | 333 |
| 17 | Flip fair coin, heads | 1/2 | 1000 |
| 18 | Digit 0–9, odd | 5/10 | 1000 |
| 19 | Random day in August, prime | 11/31 | 550 |
| 20 | Random int 1–100 divisible by 15 | 6/100 | 64 |
| 21 | Random letter, vowel (A,E,I,O,U) | 5/26 | 238 |
| 22 | Flip 3 coins, exactly 2 heads | 3/8 | 600 |
| 23 | Random day of week, weekday | 5/7 | 2500 |
| 24 | Roll 11-sided die, 1–7 | 7/11 | 1750 |
| 25 | Random month = birth month | 1/12 | 91 |
| 26 | Random int 1–20 divisible by 4 | 5/20 | 333 |
| 27 | Random int 1–20 NOT divisible by 4 | 15/20 | 3000 |
| 28 | Last phone digit = 7 | 1/10 | 111 |
| 29 | Widget NOT failure (98% pass) | 49/50 | 49000 |
| 30 | Random month, NOT birth month | 11/12 | 11000 |
For each element of an array, a counter is set to 0. The element is compared to each element to its left. If the element to the left is greater, the absolute difference is subtracted from the counter. If the element to the left is less, the absolute difference is added to the counter. For each element of the array, determine the value of the counter. These values should be stored in an array and returned.
Function Description
Complete the function arrayChallenge in the editor.
arrayChallenge has the following parameter(s):
int arr[n]: an array of integers Returnsint[n]: an array of integers calculated as described above
Example 1
Input:
arr = [2, 4, 3]
Output:
[0, 2, 0]
Explanation:
- For arr[0] = 2, counter starts at 0 and there are no elements to the left so counter = 0.
- For arr[1] = 4, counter starts at 0 and then increases by | 4 - 2 | = 2 at the first and only comparison: counter = 2.
- Testing arr[2] = 3, first against 4, counter = 0 - | 3 - 4 | = -1, and then against 2, counter = -1 + | 3 - 2 | = 0.
- The answer array is [0, 2, 0].
A manufacturing company is located in a certain city. Their goods need to be shipped to other cities that are connected with bidirectional roads, though some cities may not be accessible because roads don't connect to them. The order of deliveries is determined first by distance, then by priority. Given the number of cities, their connections via roads, and what city the manufacturing company is located in, determine the order of cities where the goods will be delivered.
Example 1
Input:
cityNodes = 4
cityFrom = [1, 2, 2]
cityTo = [2, 3, 4]
company = 1
Output:
[2, 3, 4]
Explanation: The closest city to the manufacturing company is city 2, which is 1 unit away. The next-closest cities are city 3 and city 4, which are both 2 units away. Since city 3 has a smaller number than city 4, it is visited first, followed by city 4. Thus, the order of delivery is [2, 3, 4].
Given an array, find two statistic indicators for the array and report the difference between the two stats. The indicators are defined as follows:
- Indicator 1: This is defined by the number of instances where a number
kappears for exactlykconsecutive times in the array. For example, in the array[1, 2, 2, 3, 3, 3, 1, 1, 2, 2], we have1(1),2(4),3(3),1(2),2(2)where the value in the braces represents the number of times the integer appeared consecutively. The value of indicator 1 for the given array would be3corresponding to1(1),3(3)and2(2). - Indicator 2: This is defined by the number of instances where a number
kappears for exactlykconsecutive times in the array, starting from indexkassuming 1-based indexing. For example, in the array[2, 2, 4, 4, 4, 4, 4, 4], if we start at index2we have exactly2consecutive2scoming up. While when we start at index4, we have6consecutive4scoming up. Hence the value of indicator 2 for the array would be1corresponding to the index2. Your task is to find the absolute difference between the two indicators. Function Description Complete the functiondifference_calculatorin the editor below. The function must return the difference between the two indicators.difference_calculatorhas the following parameter(s): -
n: the number of elements present in the array
-
arr[arr[0],...arr[n-1]]: an array of N integers
Constraints
- 1 ≤ N ≤ 100
- 1 ≤ arr[i] ≤ 15
Example 1
Input:
n = 14
arr = [3, 3, 2, 2, 5, 5, 5, 5, 5, 3, 3, 2, 2, 2]
Output:
3
Explanation: Indicator 1 will be 4.
- 3 3 2 2 5 5 5 5 5 3 3 2 2 2
- 2 appears exactly two consecutive times.
- 5 appears for exactly five consecutive times.
- Then, 3 appears for exactly three consecutive times.
- Then, 2 appears for exactly two consecutive times. Indicator 2 will be 1.
- 3 3 2 2 5 5 5 5 5 3 3 2 2 2
- 5 appears for exactly five times, starting from index 5. The difference is 3.
Example 2
Input:
n = 10
arr = [1, 2, 2, 4, 4, 4, 4, 2, 2, 2]
Output:
0
Explanation: Indicator 1 will be 3.
- 1 2 2 4 4 4 4 2 2 2
- 1 appears exactly once.
- 2 appears exactly two consecutive times.
- 4 appears exactly four consecutive times. Indicator 2 will be 3.
- 1 2 2 4 4 4 4 2 2 2
- 1 appears exactly once, starting from index 1.
- 2 appears exactly two consecutive times, starting from index 2.
- 4 appears exactly four consecutive times, starting from index 4. The difference is 0.
A number of cities are arranged on a simple two by two grid, which is like an ordinary Cartesian plane. Each city is located at an integral (x, y) coordinate intersection. City names and locations are given in the form of a three-part list: [NAME, X, Y] and are provided by the method to solve the problem named findNearestCities, as shown in the pseudocode below. Determine the name of the nearest city that shares either an x or a y coordinate with the queried city. If no other cities share a x or y coordinate, return "NONE". If two cities have the same distance to the queried city (i.e., if candidate cities are at an equal distance to your name [i.e., "your_city" is the closest choice. The distance is the Manhattan distance, the absolute difference in x plus the absolute difference in y.
Constraints
- 1 ≤ n, m ≤ 10⁵
- 1 ≤ x[i], y[i] ≤ 10⁹
- 1 ≤ length of q[i] and c[i] ≤ 10
- Each character of all c[i] and q[i] is in the range ascii[a-z, 0-9, -]
- All city name values, c[i], are unique
- All cities have unique coordinates
Example 1
Input:
numOfCities = 3
cities = ["c1", "c2", "c3"]
xCoordinates = [3, 2, 1]
yCoordinates = [3, 2, 3]
numOfQueries = 3
queries = ["c1", "c2", "c3"]
Output:
["3", "NONE", "c1"]
Explanation: The three cities at (3, 3), (2, 2), (1, 1) are named c1, c2, and c3 respectively. For the query "c1", the nearest city sharing an x or y coordinate is "c2" at (2, 2) with a Manhattan distance of 2. For the query "c2", the nearest city sharing an x or y coordinate is "c3" at (1, 1) with a Manhattan distance of 2. For the query "c3", the nearest city sharing an x or y coordinate is "c2" at (2, 2) with a Manhattan distance of 2.
Example 2
Input:
numOfCities = 3
cities = ["fastcity", "bigbanana", "xyz"]
xCoordinates = [23, 23, 23]
yCoordinates = [1, 10, 20]
numOfQueries = 3
queries = ["fastcity", "bigbanana", "xyz"]
Output:
["bigbanana", "fastcity", "bigbanana"]
Explanation: There are three cities in the input with the corresponding coordinates: 'fastcity' = (23, 1), 'bigbanana' = (23, 10), 'xyz' = (23, 20). The distance between 'fastcity' and 'bigbanana' is 9, 'fastcity' to 'xyz' is 19, and 'bigbanana' to 'xyz' is 10. There are three queries to answer. The first of them asks for the closest city to 'fastcity’, which has exactly one different coordinate. Both 'bigbanana' and 'xyz' have exactly one coordinate that differs from 'fastcity’, but 'bigbanana' is closer and is the correct answer. The second query asks for the closest direct city to 'bigbanana’, and since 'fastcity' is closer than 'xyz’, the correct answer is 'fastcity’. The third query asks for the closest direct city to 'xyz’, and since 'bigbanana' is closer than 'fastcity’, the correct answer is 'bigbanana’.
Example 3
Input:
numOfCities = 3
cities = ["london", "warsaw", "hackerland"]
xCoordinates = [1, 10, 20]
yCoordinates = [1, 10, 10]
numOfQueries = 3
queries = ["london", "warsaw", "hackerland"]
Output:
["NONE", "warsaw", "hackerland"]
Explanation: The cities are located as follows: 'london' = (1, 1), 'warsaw' = (10, 10), and 'hackerland' = (20, 10). There are no other cities on a row or column shared with 'london', so the first query returns 'NONE'. The cities of 'warsaw' and 'hackerland' share y values, so they are the closest to each other.
Example 4
Input:
numOfCities = 5
cities = ["green", "red", "blue", "yellow", "pink"]
xCoordinates = [100, 200, 300, 400, 500]
yCoordinates = [100, 200, 300, 400, 500]
numOfQueries = 5
queries = ["green", "red", "blue", "yellow", "pink"]
Output:
["NONE", "NONE", "NONE", "NONE", "NONE"]
Explanation: None of the cities share a row or a column, so none meet the criteria for being considered closest to the queried city.
Lily is in the final round of the Optimized Waffle Baking Championship hosted in Bieslau, Ida. Her opponent baked first and surprisingly has a high score, meaning that Lily must score an exact number of points to win. If she scores too many points, or too few points, her opponent will take home the championship trophy instead. Lily will have a finite number of chances (or "bakes") to make waffles for all the judges, and on each bake she can choose from any of her waffle mixes. Each waffle mix affords her a different probability to score anywhere from 1 to 5 points, or 0 points if she is unable to submit a waffle in time. She can use the same baking mix any number of times, and she does not have to use each of the mixes at all. At any point, Lily can choose to stop baking waffles; she would do this only if she reaches her target score before using up all of her chances, thereby avoiding going over. Having been an amateur baker most of her life, Lily knows the exact probability distribution of each of her available waffle mixes.
Assume that Lily takes an optimal strategy in her quest to win the championship, and that each bake is independent of the others. Implement the function getProbability to determine the probability that Lily takes home the championship trophy.
Function Description
Complete the function getProbability in the editor.
getProbability has the following parameters:
int[] scores: The array of scores that Lily can potentially earn with each of her waffle mixes.int[] prob: The array of probabilities, in percentage points, that Lily will earn the number of points represented by the corresponding element in the scores array.int n: The number of chances Lily has to bake waffles.int x: The exact number of points Lily needs to win the championship. Returns double: The probability, as a double, that Lily wins the championship given the parameters. Helper Functions Two helper functions are available for calculating compound probabilities:probabilityAND(double a, double b): Calculates the probability of two independent events both occurring.probabilityOR(double a, double b): Calculates the probability of at least one of two independent events occurring.
Example 1
Input:
scores = [2, 3, 5]
prob = [10, 10, 20]
n = 2
x = 6
Output:
0.013
Explanation: Consider a scenario in which Lily has 2 bakes available, 3 waffle mixes from which to choose, and is trying to earn exactly 6 points. The probability distribution for the waffle mixes is as follows:
- Mix 1: 10% chance of 2 points, 10% chance of 3 points, 20% chance of 5 points.
- Mix 2: 20% chance of 1 point, 20% chance of 2 points, 20% chance of 3 points, 10% chance of 4 points, and 10% chance of 5 points.
- Mix 3: 20% chance of 1 point, 30% chance of 2 points, 20% chance of 3 points, 10% chance of 4 points, and 20% chance of 5 points. The final calculated probability is then 0.013.
There is a string input_str consisting of characters '0' and '1' only and an integer k. Find a substring of string input_str such that:
The number of '1's is equal to k
It has the smallest length
It is lexicographically smallest
Note: It is guaranteed that answer always exists.
Function Description
Complete the function getSubstring in the editor below.
getSubstring has the following parameters:
- string
input_str: a string that consists of '0' and '1' - int
k: the number of '1's in the answer Returns string: the substring that meets the given conditions
Constraints
- 1 ≤ k ≤ length of s ≤ 10³
- s[i] is in the set {'0', '1'}
- The number of '1' characters in string
Example 1
Input:
input_str = "0101101"
k = 3
Output:
"1011"
Explanation: Some of the possible substrings following the first condition:
- "01011"
- "1101"
- "1011" The substring that is smallest in length and lexicographically smallest is "1011". It can be proven that there is no other substring that is smaller than "1011" in length and lexicographic order. Hence the answer is "1011".
Given an array of n item values, sort the array in ascending order, first by the frequency of each value, then by the values themselves.
Function Description
Complete the function itemsSort in the editor below.
itemsSort has the following parameter(s):
int items[n]: the array to sort Returnsint[n]: the sorted array
Constraints
1 ≤ n ≤ 2 x 10⁵¹ ≤ items[i] ≤ 10⁶
Example 1
Input:
items = [4, 5, 6, 5, 4, 3]
Output:
[3, 6, 4, 4, 5, 5]
Explanation: There are 2 values that occur once: [3, 6]. There are 2 values that occur twice: [4, 4, 5, 5]. The array of items sorted by frequency and then by value in ascending order is [3, 6, 4, 4, 5, 5].
Christine and her friends are planning a movie marathon using her family's massive film library. They want to start with shorter movies and progress onto longer movies, but they're going to do it in a very specific way: each movie they watch must be the same length as the previous movie, or exactly one minute longer than the previous movie (counting opening and closing credits, of course). The first movie they watch can have any length. They do not want to watch any of the movies twice, even if they're not back-to-back. Popcorn will be provided.
Assume that Christine and her friends plan their movie marathon optimally. Implement the following function in the code editor to determine the maximum number of movies that the group can watch according to their rules.
Function Description
Complete the function longestMarathon in the editor.
longestMarathon has the following parameter:
int[] runtimes: an array of integers representing the collection of movie runtimes Returns int: the length of the largest sequence of non-repeated movies that the group can watch, such that the Nth movie in the sequence has the same runtime as, or is exactly one minute longer than, the (N-1)st movie. A return value of 0 indicates that it is not possible for the group to have a marathon at all.
Constraints
N/A
Example 1
Input:
runtimes = [8, 4, 5, 7, 4]
Output:
3
Explanation: Consider a film library that consists of 5 films whose runtimes are [8, 4, 5, 7, 4].
- If the group starts with film 0 whose runtime is 8, their marathon will have length 1, as all the other movies have shorter runtimes.
- If the group starts with film 1 or film 4, each of which has a runtime of 4, they have two options to progress:
- They can watch the other film with a runtime of 4, and then film 2 whose runtime is 5, giving their marathon a length of 3
- They can immediate jump to film 2 whose runtime is 5, giving their marathon a length of 2
- If the group starts with film 2 whose runtime is 5, their marathon will have length 1, as there are no other film whose runtime is either 5 or 6
- If the group starts with film 3 whose runtime is 7, they can then watch film 0 whose runtime is 8, giving their marathon a length of 2 The function should therefore return 3.
A product manager has to organize n meetings with different people. Meeting with each person results in an increase or decrease in the effectiveness index of the manager. The manager wants to organize the meetings such that the index remains positive for as many meetings as possible. Find the maximum number of meetings for which the effectiveness index is positive. The index at the beginning is 0.
Note: After the meetings begin, the index must remain above 0 to be positive.
Function Description
Complete the function maxMeetings in the editor.
maxMeetings has the following parameter:
int effectiveness[n]: the increase or decrease effectiveness for each meeting. Returnsint: the maximum possible number of meetings while maintaining a positive index
Constraints
- 1 ≤ n ≤ 10⁵
- -10⁹ ≤ effectiveness[i] ≤ 10⁹
Alex loves movies and maintains a list of negative and/or positive integer ratings for the movies in a collection. Alex is getting ready for a film festival and wants to choose some subsequence of movies from the collection to bring such that the following conditions are satisfied:
- The collective sum of their ratings is maximal.
- Alex must go through the list in order and cannot skip more than one movie in a row. In other words, Alex cannot skip over two or more consecutive movies. For example, if ratings = [-1, -3, -2], and must include either the second number or the first and third numbers to get a maximal rating sum of -3.
Function Description
Complete the function
maximizeRatingsin the editor below.maximizeRatingshas the following parameter(s): int ratings[n]: movie ratings Returns int: the maximum sum of the ratings of the chosen subsequence of movies
Constraints
- 1 ≤ n ≤ 10⁵
- -1000 ≤ ratings[i] ≤ 1000, where 0 ≤ i < n
Example 1
Input:
ratings = [-3, 2, 4, -1, -2, -5]
Output:
4
Explanation: The maximal choices are [2, 4, -2] for a sum of 4.
Example 2
Input:
ratings = [9, -1, -3, 4, 5]
Output:
17
Explanation: Alex picks the bolded items in ratings = [9, -1, -3, 4, 5] to get maximum rating = 9 + 4 + 5 = 17.
An engineer is working to build an integrated binary circuit that takes input a binary string. A binary string consisting of only 0s and 1s can be segregated by moving all the 1s towards the end of the string. For example, the string "01010", after segregation becomes "00011".
In a single operation, any "1" from the binary string can be chosen and moved to the right until it reaches the end of the string or another "1". The cost of the operation is 1 + the number of places the one is moved. For example, in the string "100010", the first one can be moved three places to the right in cost 4. Note that it is mandatory to move a 1 to the maximum possible position to the right.
Given a binary string s, find the maximum number of operations possible to segregate the given string.
Function Description
Complete the function maximizeSegregationCost in the editor.
maximizeSegregationCost has the following parameter:
String s: a binary string Returns int: the maximum number of operations possible to segregate the given string
Constraints
N/A
Given an unordered list of future stock prices, what is the maximum amount of profit that you could generate from a starting amount of $1,000.00 Rules: You can trade fractional shares (e.g. if there were shares for $400.00, you could buy/sell 2.5 of them for $1,000.00) All trades occur instantaneously and do not incur any transaction costs. Shares may only be bought/sold on a date that you have a known price. Short selling is not allowed. You do not need to have a position at all times (at any time, if you cannot identify a profitable trade, you do not have to trade). Round final answer to nearest dollar. Do not assume input tuple will be sorted in any manner. Future prices will be given as a list in the following format: [Stock, Date, Price]
Constraints
N/A
Example 1
Input:
prices = ["CSCO,10/18/2024,41.89", "AMZN,10/10/2024,113.67", "AMZN,10/18/2024,120.5", "CSCO,10/10/2024,43.12"]
Output:
60
Explanation: Buy 8.797 AMZN @ $113.67 on 10/10/2024 and sell @ $120.5 on 10/18/2024. Profit = $60
Example 2
Input:
prices = ["IBM,12/01/2023,132.05", "IBM,12/18/2023,134.07", "AAPL,12/01/2023,187.19", "AAPL,12/04/2023,164.33", "AAPL,12/20/2023,180.94", "AAPL,12/21/2023,179.65", "GOOG,12/01/2023,116.41", "GOOG,12/07/2023,111.36", "GOOG,12/19/2023,112.19"]
Output:
127
Explanation: Buy 7.573 IBM @ $132.05 on 12/01/2023 and sell @ $135.19 on 12/3/2023. Buy 6.230 AAPL on 12/4/2023 @ $164.33 and sell on 12/20/2023 @ $180.94. Profit = $127
Example 3
Input:
prices = ["INTC, 12/01/2023, 30.00", "INTC, 12/05/2023, 35.00", "INTC, 12/10/2023, 33.00", "AAPL, 12/02/2023, 150.00", "AAPL, 12/06/2023, 155.00", "AAPL, 12/11/2023, 160.00", "INTC, 12/15/2023, 36.00" "INTC, 09/10/2024, 36.26", "INTC, 12/04/2023, 33.39", "AAPL, 12/22/2023, 197.61", "AAPL, 07/20/2025, 181.71", "INTC, 10/27/2024, 35.66", "AAPL, 01/30/2025, 178.68", "AAPL, 12/21/2024, 176.22", "AAPL, 05/14/2024, 182.66", "INTC, 08/15/2024, 35.23", "AAPL, 02/20/2025, 196.47", "INTC, 03/29/2025, 32.13", "INTC, 06/28/2025, 32.96", "INTC, 07/11/2025, 35.63"]
Output:
343
Explanation:
A player stands on a cell within a grid. The player can move to one of four adjacent cells, but the motion is constrained by lasers. To move from one position to another involves a cost: the cost to move from row i to row i ± 1 is costRows[i] and the cost to move from column j to column j ± 1 is costCols[j]. Find the minimum cost to move from a starting point to an ending point within the grid.
Function Description
Complete the function minCost in the editor below.
minCost has the following parameters:
int rows: the number of rows in the gridint cols: the number of columns in the gridint initR: the player's starting rowint initC: the player's starting columnint finalR: the goal's rowint finalC: the goal's columnint costRows[n]: eachcostRows[i]denotes the cost to move between rows i and i + 1.int costCols[m]: eachcostCols[j]denotes the cost to move between columns j and j + 1. Returnsint: the minimum cost to move from the starting position to the goal
Constraints
1 ≤ rows, cols ≤ 10⁵- `0 ≤ initR, finalR
Example 1
Input:
rows = 3
cols = 3
initR = 0
initC = 0
finalR = 1
finalC = 2
costRows = [5, 2]
costCols = [6, 1]
Output:
9
Explanation: The player must move down one row (cost = 2) and over two columns (cost = 6 + 1 = 7) for a total cost of 2 + 7 = 9.
Example 2
Input:
rows = 4
cols = 4
initR = 1
initC = 2
finalR = 3
finalC = 3
costRows = [1, 2, 3]
costCols = [7, 8, 9]
Output:
14
Explanation: The player must move from row 1 to row 3 for a cost = 2 + 3 = 5 and then from column 2 to column 3 for a cost of 9. The total cost is 5 + 9 = 14.
For each word in a list of words, if any two adjacent characters are equal, change one of them. Determine the minimum number of substitutions so the final string contains no adjacent equal characters.
Function Description
Complete the function minimalOperations in the editor below.
minimalOperations has the following parameter(s):
string words[n]: an array of strings Returnsint[n]: each element is the minimum substitutions for words[i]
Constraints
- 1 ≤ n ≤ 100
- 2 ≤ length of words[i] ≤ 10⁵
- Each character of words[i] is in the range ascii[a-z].
Example 1
Input:
words = ["add", "boook", "break"]
Output:
[1, 1, 0]
Explanation:
- 'add': change one d (1 change)
- 'boook': change the middle o (1 change)
- 'break': no changes are necessary (0 changes) The return array is [1, 1, 0].
A financial services company is uploading documents to a compliance system for analysis. They use a chunking mechanism as below.
- Each document is divided into equal sized packets.
- Documents are then divided and uploaded in "chunks" of packets. A chunk is defined as a contiguous collection of 2^n packets, where n is any integer ≥ 0.
- After the document is divided into chunks, randomly selected chunks are uploaded until the entire document is completely uploaded.
There is one document that is partially uploaded, described in uploadedChunks. Determine the minimum number of chunks that are yet to be uploaded.
Function Description
Complete the function
minimumChunksRequiredin the editor.minimumChunksRequiredhas the following parameter(s): long totalPackets: the number of packets in the document.long uploadedChunks[n][2]: each uploadedChunks[i] describes the start and end packet numbers of the uploaded chunks. Returnsint: an integer that denotes the minimum number of chunks that need to be uploaded.
Constraints
- 1 ≤ totalPackets < 10¹⁸
- 0 ≤ uploaded < 10⁵
- The uploaded chunks do not overlap
- 1 ≤ starting packet ≤ ending packet ≤ totalPackets
Example 1
Input:
totalPackets = 10
uploadedChunks = [[1, 2], [9, 10]]
Output:
2
Explanation: The document has 10 packets and 2 chunks of 2¹ = 2 packets are already uploaded [1, 2] and [9, 10]. The remaining 10-4 = 6 packets are uploaded in chunks. The length of chunk1 is 2² = 4, packets [3,4,5,6], and the length of chunk2 is 2⁰ = 1 packets [7, 8].
Example 2
Input:
totalPackets = 18
uploadedChunks = [[9, 17]]
Output:
2
Explanation: The document has 18 packets and 2 chunks of packets are already uploaded: [9, 10, 11, 12, 13, 14, 15, 16] and [17]. The remaining 18-2 = 16 packets are uploaded in chunks. The length of chunk1 is 2³ = 8 packets: [1, 2, 3, 4, 5, 6, 7, 8] and the length of chunk2 is 2⁰ = 1 packets: [18].
As a lion trainer, you are taking part in an international lion exhibition. During the event lions from different teams enter and exit the showroom where lion experts inspect and score them. Lions do not enter the showroom all at once, as that would cause too much commotion. The organizers of the event let them in and out based on a predefined schedule. Before the show you are given the schedule for your lions, but not for the others. During the show, however, you can observe all lions entering and exiting the room. Based on your experience, you believe that judges tend to award the largest lions with the highest scores. Before the final results are out, you want to estimate your chances of winning this competition. Problem Statement Complete the following:
- The LionCompetition class constructor that accepts lion descriptions and the private schedule for your lions.
- The LionEntered and LionLeft methods that are called whenever a new lion enters or leaves the room.
- The getBiggestLions method that, for the current time, returns a list of our lions in the room that are at least as large as the largest lion from competing teams in the room, sorted alphabetically. Function definitions LionCompetition class constructor parameters:
- lions - list of elements describing your lions:
- name - string representing a name of the lion
- height - height of the lion
- schedule - a private schedule of when your lions enter and leave the show room
- name - string representing a name of the lion
- enterTime - number of minutes since the start of the show when the lion will enter the room
- exitTime - number of minutes since the start of the show when the lion will exit the room LionEntered function parameters:
- currentTime - number of minutes since the start of the show
- height - height of the lion that entered the room LionLeft function parameters:
- currentTime - number of minutes since the start of the show
- height - height of the lion that left the room
Constraints
- Subsequent invocations of LionLeft and LionEntered methods are always called in order, according to the currentTime parameter.
- The schedule is strictly followed - your lions enter and exit the room exactly at their specified times.
- The lion inspection (invocation of the getBiggestLions method) takes place either before or after all lions scheduled to enter or leave the room at a given minute did that - never in between.
- Lion names are unique.
- Times (currentTime, enterTime and exitTime) are always whole numbers (and multiple events can occur at the same time).
- A single lion enters the room only once during the show.
解锁全部 24 道题的解法
题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.
- 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
- 📊个人 dashboard + 进度可视化 + 14 天活跃图
- 📝题目笔记跨设备同步 + 个人复盘库
- 🔓随时取消下次续费, Stripe Customer Portal 自助管理