OAmaster
— / 22已做

Given an array arr of n integers, the goodness of a strictly increasing subsequence is the bitwise OR of its elements. The empty subsequence has goodness 0. Return the number of distinct goodness values obtainable.

Example: arr = [4, 2, 4, 1] → distinct goodness {0, 1, 2, 4, 6}5.

解法

按下标 DP:dp[i] 是以 i 结尾的严格递增子序列的所有 OR 值集合。对每个 j < iarr[j] < arr[i],把 dp[j] 内的值与 arr[i] OR 后并入 dp[i]。最后并所有 dp[i] 加上空子序列。复杂度 O(n² · |dp|),实际中 OR 集合规模很小。

def distinct_goodness(arr):
    n = len(arr)
    dp = []
    all_ = {0}
    for i in range(n):
        cur = {arr[i]}
        for j in range(i):
            if arr[j] < arr[i]:
                for x in dp[j]:
                    cur.add(x | arr[i])
        dp.append(cur)
        all_ |= cur
    return len(all_)
import java.util.*;

class Solution {
    int distinctGoodness(int[] arr) {
        int n = arr.length;
        List<Set<Integer>> dp = new ArrayList<>();
        Set<Integer> all = new HashSet<>();
        all.add(0);
        for (int i = 0; i < n; i++) {
            Set<Integer> cur = new HashSet<>();
            cur.add(arr[i]);
            for (int j = 0; j < i; j++) {
                if (arr[j] < arr[i]) {
                    for (int x : dp.get(j)) cur.add(x | arr[i]);
                }
            }
            dp.add(cur);
            all.addAll(cur);
        }
        return all.size();
    }
}
#include <vector>
#include <unordered_set>
using namespace std;

int distinctGoodness(vector<int>& arr) {
 int n = arr.size();
 vector<unordered_set<int>> dp(n);
 unordered_set<int> all_;
 all_.insert(0);
 for (int i = 0; i < n; i++) {
 dp[i].insert(arr[i]);
 for (int j = 0; j < i; j++) {
 if (arr[j] < arr[i]) {
 for (int x : dp[j]) dp[i].insert(x | arr[i]);
 }
 }
 for (int v : dp[i]) all_.insert(v);
 }
 return (int) all_.size();
}

Given n users and a friendship matrix friends[n][n] where friends[i][j] = '1' if i and j are friends. For each user, recommend the non-friend with the maximum number of common friends. Break ties by smallest index. Return an array rec[n] where rec[i] = -1 if no candidate exists.

Example: friends = ["010","100","000"] → for user 2 no friend exists; both users 0 and 1 have only each other.

解法

把每行压成位掩码。对每对非好友的下标 (i, j),共同好友数即 popcount(mask[i] & mask[j])。对每个 i 记录最优 j。复杂度 O(n² · n / 64)

def friend_recommendation(friends):
    n = len(friends)
    masks = [int(''.join(reversed(s)), 2) for s in friends]
    rec = []
    for i in range(n):
        best, best_cnt = -1, -1
        for j in range(n):
            if i == j or friends[i][j] == '1':
                continue
            cnt = bin(masks[i] & masks[j]).count('1')
            if cnt > best_cnt or (cnt == best_cnt and (best == -1 or j < best)):
                best, best_cnt = j, cnt
        rec.append(best)
    return rec
import java.util.*;
import java.math.BigInteger;

class Solution {
    int[] friendRecommendation(String[] friends) {
        int n = friends.length;
        BigInteger[] masks = new BigInteger[n];
        for (int i = 0; i < n; i++) {
            StringBuilder rev = new StringBuilder(friends[i]).reverse();
            masks[i] = new BigInteger(rev.toString(), 2);
        }
        int[] rec = new int[n];
        for (int i = 0; i < n; i++) {
            int best = -1, bestCnt = -1;
            for (int j = 0; j < n; j++) {
                if (i == j || friends[i].charAt(j) == '1') continue;
                int cnt = masks[i].and(masks[j]).bitCount();
                if (cnt > bestCnt || (cnt == bestCnt && (best == -1 || j < best))) {
                    best = j; bestCnt = cnt;
                }
            }
            rec[i] = best;
        }
        return rec;
    }
}
#include <vector>
#include <string>
#include <bitset>
using namespace std;

vector<int> friendRecommendation(vector<string>& friends) {
 int n = friends.size();
 vector<vector<int>> mask(n, vector<int>(n, 0));
 for (int i = 0; i < n; i++)
 for (int j = 0; j < n; j++)
 mask[i][j] = (friends[i][j] == '1');
 vector<int> rec(n);
 for (int i = 0; i < n; i++) {
 int best = -1, bestCnt = -1;
 for (int j = 0; j < n; j++) {
 if (i == j || friends[i][j] == '1') continue;
 int cnt = 0;
 for (int k = 0; k < n; k++) cnt += mask[i][k] & mask[j][k];
 if (cnt > bestCnt || (cnt == bestCnt && best == -1)) {
 best = j; bestCnt = cnt;
 }
 }
 rec[i] = best;
 }
 return rec;
}

Given a binary string s ('0'/'1'), return the number of length-5 palindromic subsequences modulo 10⁹ + 7.

Example: s = "10110" → count subsequences of the form aXbXa with a, b ∈ {0, 1}.

解法

长度 5 回文形如 a b c b a。固定中间下标 m,定义 leftBA[m][b*2+a]m 左侧按 ab 顺序的选法数,rightBA[m][b*2+a] 为右侧同理。答案 = Σ_{m,a,b} leftBA[m][b*2+a] * rightBA[m+2][b*2+a]。复杂度 O(n)

def count_palindromic_subseq5(s):
    MOD = 10**9 + 7
    n = len(s)
    leftBA = [[0] * 4 for _ in range(n + 1)]
    leftA = [0, 0]
    for i in range(n):
        for k in range(4): leftBA[i + 1][k] = leftBA[i][k]
        x = int(s[i])
        for b in range(2):
            leftBA[i + 1][b * 2 + x] = (leftBA[i + 1][b * 2 + x] + leftA[b]) % MOD
        leftA[x] += 1
    rightBA = [[0] * 4 for _ in range(n + 2)]
    rightA = [0, 0]
    for i in range(n - 1, -1, -1):
        for k in range(4): rightBA[i + 1][k] = rightBA[i + 2][k]
        x = int(s[i])
        for b in range(2):
            rightBA[i + 1][b * 2 + x] = (rightBA[i + 1][b * 2 + x] + rightA[b]) % MOD
        rightA[x] += 1
    ans = 0
    for m in range(n):
        for a in range(2):
            for b in range(2):
                ans = (ans + leftBA[m][b * 2 + a] * rightBA[m + 2][b * 2 + a]) % MOD
    return ans
class Solution {
    int countPalindromicSubseq5(String s) {
        final int MOD = 1_000_000_007;
        int n = s.length();
        long[][] leftBA = new long[n + 1][4];
        long[] leftA = new long[2];
        for (int i = 0; i < n; i++) {
            for (int k = 0; k < 4; k++) leftBA[i + 1][k] = leftBA[i][k];
            int x = s.charAt(i) - '0';
            for (int b = 0; b < 2; b++)
                leftBA[i + 1][b * 2 + x] = (leftBA[i + 1][b * 2 + x] + leftA[b]) % MOD;
            leftA[x]++;
        }
        long[][] rightBA = new long[n + 2][4];
        long[] rightA = new long[2];
        for (int i = n - 1; i >= 0; i--) {
            for (int k = 0; k < 4; k++) rightBA[i + 1][k] = rightBA[i + 2][k];
            int x = s.charAt(i) - '0';
            for (int b = 0; b < 2; b++)
                rightBA[i + 1][b * 2 + x] = (rightBA[i + 1][b * 2 + x] + rightA[b]) % MOD;
            rightA[x]++;
        }
        long ans = 0;
        for (int m = 0; m < n; m++)
            for (int a = 0; a < 2; a++)
                for (int b = 0; b < 2; b++)
                    ans = (ans + leftBA[m][b * 2 + a] * rightBA[m + 2][b * 2 + a]) % MOD;
        return (int) ans;
    }
}
#include <string>
#include <vector>
using namespace std;

int countPalindromicSubseq5(string s) {
 const int MOD = 1e9 + 7;
 int n = s.size();
 vector<vector<long long>> leftBA(n + 1, vector<long long>(4, 0));
 long long leftA[2] = {0, 0};
 for (int i = 0; i < n; i++) {
 for (int k = 0; k < 4; k++) leftBA[i + 1][k] = leftBA[i][k];
 int x = s[i] - '0';
 for (int b = 0; b < 2; b++)
 leftBA[i + 1][b * 2 + x] = (leftBA[i + 1][b * 2 + x] + leftA[b]) % MOD;
 leftA[x]++;
 }
 vector<vector<long long>> rightBA(n + 2, vector<long long>(4, 0));
 long long rightA[2] = {0, 0};
 for (int i = n - 1; i >= 0; i--) {
 for (int k = 0; k < 4; k++) rightBA[i + 1][k] = rightBA[i + 2][k];
 int x = s[i] - '0';
 for (int b = 0; b < 2; b++)
 rightBA[i + 1][b * 2 + x] = (rightBA[i + 1][b * 2 + x] + rightA[b]) % MOD;
 rightA[x]++;
 }
 long long ans = 0;
 for (int m = 0; m < n; m++)
 for (int a = 0; a < 2; a++)
 for (int b = 0; b < 2; b++)
 ans = (ans + leftBA[m][b * 2 + a] * rightBA[m + 2][b * 2 + a]) % MOD;
 return (int) ans;
}

Given a string s, return the number of distinct palindromic substrings.

Example: s = "ababa"{"a","b","aba","bab","ababa"}5.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given parent[n] (with parent[root] = -1) and values[n], find the maximum sum of a downward path (ancestor → descendant) in the rooted tree.

Example: tree 0:5 → 1:3, 2:-1, child of 1: 3:4 → best path 0 → 1 → 3 sums to 12.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given strings text, prefixString, suffixString. For a substring t of text:

  • prefixScore(t) = length of the longest suffix of prefixString that equals a prefix of t.
  • suffixScore(t) = length of the longest prefix of suffixString that equals a suffix of t.
  • score(t) = prefixScore(t) + suffixScore(t).

Return the substring of text with the maximum score; ties broken by lexicographic order.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n jobs that can run in parallel. Job i has executionTime[i]. In one operation we pick a majorJob: it runs for x seconds while every other still-pending job runs for y seconds (y < x). A job is complete when its remaining time ≤ 0. Find the minimum number of operations.

Example: executionTime = [3, 4, 1, 7, 6], x = 4, y = 23.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given an array memoryBlocks[n]. In one operation, choose an index x and increase memoryBlocks[x] by 1. After 0 or more operations, the Valid Size is MEX(memoryBlocks) — the smallest non-negative integer not present. Return the sorted array of all possible Valid Sizes obtainable.

Example: memoryBlocks = [0, 2, 4] → start MEX = 1; after +1 on index 0 → [1, 2, 4] MEX = 0. Answer: [0, 1].

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A company employee earns fixedPay per workday and a bonus on a day if they also worked the previous day. The schedule is a binary string schedule of length n ('1' = workday, '0' = off). The employee can change at most k days from '0' to '1'. Return the maximum total earnings.

Example: n = 5, k = 1, fixedPay = 10, bonus = 3, schedule = "10110" → flip one 0 to maximize bonus chains.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

In a distributed network with n packets numbered 1..n, the checksum between packets i and j is C(i, j) = (i mod j) + (j mod i). Return (Σ Σ C(i, j)) mod (10⁹ + 7) over 1 ≤ i, j ≤ n.

Example: n = 3 → small cases enumerable by hand.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n developers; the i-th developer has skill level i (1-indexed, 1..n). Each developer i (1-indexed) agrees to join only if at most lowerSkill[i-1] chosen team members have a lower skill level than them, and at most higherSkill[i-1] have a higher skill level. Maximize the team size.

Example: n = 5, lowerSkill = [1, 3, 2, 2, 2], higherSkill = [2, 2, 1, 1, 3] → pick developers {1, 3, 4} → size 3.

Constraints

1 ≤ n ≤ 2*10⁵, 0 ≤ lowerSkill[i], higherSkill[i] < n.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

In an organization, there are n servers, each with a capacity of capacity[i]. A contiguous subsegment[l, r] of servers is said to be stable if capacity[i] = capacity[r] = sum[l + 1, r - 1]. In other words, the capacity of the servers at the endpoints of the segment should be equal to the sum the sum of the capacities of all the interior servers. Find the num of stable sub-segments of length 3 or more. Function Description Complete the function countStableSegments in the editor. countStableSegments has the following parameters:

  • int[] capacity: the capacity of each server Returns int: the num of stable segments

Constraints

  • 1 ≤ n ≤ 10⁵
  • 1 ≤ capacity[i] ≤ 10⁵

Example 1

Input:

capacity = [9, 3, 3, 3, 9]

Output:

2

Explanation: There are 2 stable subsegments: [3, 3, 3] and [9, 3, 3, 3, 9]. Return 2.

Example 2

Input:

capacity = [9, 3, 1, 2, 3, 9, 10]

Output:

2

Explanation: The stable segments are [9, 3, 1, 2, 3, 9] and [3, 1, 2, 3] :D

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The developers working on a social media network app want to analyze user behavior. There are n event logs where userEvent[i] denotes the userId for the user that triggered the i^th event. The team wants to analyze the subarray of the logs which are consistent, that is, the frequency of the most frequent user in the subarray is equal to the frequency of the least frequent user in the whole array. Find the maximum length of consistent logs. Note: A subarray is a contiguous group of elements in an array. Function Description Complete the function findConsistentLogs in the editor . findConsistentLogs has the following parameters:

  • int userEvent[n]: the userIds present in the event logs Returns int: the maximum length of consistent logs

Constraints

  • 1 ≤ n ≤ 3 * 10⁵
  • 1 ≤ userEvent[i] ≤ 10⁹

Example 1

Input:

userEvent = [1, 2, 1, 3, 4, 2, 4, 3, 3, 4]

Output:

8

Explanation:

  • The frequencies of 1 and 2 are 2
  • The frequencies of 3 and 4 are 3 The minimum frequency in the array is 2 The longest valid subarray has 8 elements: [1, 2, 1, 3, 4, 2, 4, 3]
  • The frequencies of 1, 2, 3, and 4 are all 2. The frequenccy of the most common element in the subarray is 2, the same as the min frequency in the entire array. Hence, the max len of the consistent logs is 8 :)
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

To make learning more interactive and fun for students, a math teacher decides to teach a concept to students by using Lego blocks. There are 2 rows of legos, rowA (of length n) and rowB (of length m). Both rows hold legos with positive integer values printed on them. However, some values (possibly, none) are missing. The missing values are denoted by 0. Students need to incorporate the missing values. The task is to replace each 0 with a positive integer such that the sums of both arrays are equal. Return the minimum sum possible. If it is not possible to make the sums equal, return -1. Function Description Complete the function findMinimumEqualSum in the editor. findMinimumEqualSum has the following parameters:

    1. int rowA[n]: one row of integers
    1. int rowB[m]: another row of integers Returns int: an integer, which, if positive, denotes the minimum equal sum, and if -1 indicates that it is not possible to obtain an equal sum.

Constraints

  • 1 ≤ n, m ≤ 10⁵
  • 0 ≤ rowA[i], rowB[j] ≤ 10⁴
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A coding competition organized to hire software developers includes an interesting problem on Bitwise-OR. The goodness of a sequence is defined as the bitwise-OR of its elements. Given an array arr of length n, find all possible distinct values of goodness that can be obtained by choosing any strictly increasing subsequence of the array. Sort the return array in non-decreasing order. Note: A subsequence is a sequence that can be derived from the given sequence by deleting zero or more elements without changing the order of the remaining elements. Function Description Complete the function getDistinctGoodnessValues in the editor below. getDistinctGoodnessValues has the following parameter:

  • int arr[n]: an array of integers Returns int[]: all possible distinct values of goodness

Constraints

  • 1 ≤ n, m ≤ 10⁴
  • 1 ≤ arr[i] < 1024

Example 1

Input:

arr = [4, 2, 4, 1]

Output:

[0, 1, 2, 4, 6]

Explanation: The strictly increasing subsequences which can be chosen to have distinct goodness values are:

  • Empty subsequence; goodness = 0
  • [1]; goodness = 1
  • [2]; goodness = 2
  • [4]; goodness = 4
  • (2, 4); goodness = 6 There are no other strictly increasing subsequences that yield a different goodness value. So, the answer is [0, 1, 2, 4, 6], which is sorted in non-decreasing order.

Example 2

Input:

arr = [3, 2, 4, 6]

Output:

[0, 2, 3, 4, 6, 7]

Explanation: The strictly increasing subsequences which can be chosen to have distinct goodness values are:

  • Empty subsequence; goodness = 0
  • [2]; goodness = 2
  • [3]; goodness = 3
  • [4]; goodness = 4
  • [6]; goodness = 6
  • (3, 4); goodness = 7 There are no other strictly increasing subsequences that yield a different goodness value. So, the answer is [0, 2, 3, 4, 6, 7], which is sorted in non-decreasing order.

Example 3

Input:

arr = [3, 5, 5, 5, 1]

Output:

[0, 1, 3, 5, 7]

Explanation: The strictly increasing subsequences which can be chosen to have distinct goodness values are:

  • Empty subsequence; goodness = 0
  • [1]; goodness = 1
  • [3]; goodness = 3
  • [5]; goodness = 5
  • (3, 5); goodness = 7 There are no other strictly increasing subsequences that yield a different goodness value. So, the answer is [0, 1, 3, 5, 7], which is sorted in non-decreasing order.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

A data processing pipeline consists of n services connected in a series where output of the i^th service serves as the input of the (i + 1)^th service. However, the processing units have varying latenciesl, and the throughput of the i^th units is represented by the array throughput[i] in messages per minute. The first service receives input through an API, and the n^th service produces the final output. Each service can be scaled up independently, with the cost of scaling up the i^th service on unit equal to scaling_cost[i]. After scaling up a service x times, it can process throughput[i] * (i + x) messages per minute. Given the arrays throughput and scaling_cost, both of size n, and an integer budget representing the budget available, determine the optimal scaling configuration for the services such that the throughput generated by the n^th service is maximized. Function Description Complete the function getMaxThroughput in the editor . getMaxThroughput has the following parameters:

    1. int throughput[n]: the throughput generated by each of the n services
    1. int scaling_cost[n]: the cost of scaling up a service one time
    1. int budget: the available memory Returns long: the max value of the throughput generated at the end of the composite service after scaling within the budget. Key insight: consider all feasible sol'ns Binary search across all possible throughput values, checking if can be attained within budget ᡣ • . • 𐭩 Much appreciation to Aura Man!

Constraints

404 not found

Example 1

Input:

throughput = [4, 2, 7]
scaling_cost = [3, 5, 6]
budget = 32

Output:

10

Explanation: To maximize the throughput of the final service, an optimal solution is: When these units are applied in series, they generate a throughput of 10 units, the max possible throughput given the budget. Hence the answer is 10.

Example 2

Input:

throughput = [7, 3, 4, 6]
scaling_cost = [2, 5, 4, 3]
budget = 25

Output:

9

Explanation: To maximize the throughput of the final service, an optimal solution is:

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There are n jobs that can be executed in parallel on a processor, where the execution time of the i^th job is executionTime[i]. To spped up execution, the following strategy is used. In one operation, a job is chosen, the major job, and is executed for x seconds. All other jobs are executed for y seconds where y Function Description Complete the function citadelGetMinOperations in the editor . citadelGetMinOperations has the following parameters:

  • int executionTime[n]: the execution times for each job
  • int x: the time for which the major job is executed
  • int y: the time for which all other jobs are executed executed Returns int: the min number of operations in which the processor can complete the jobs

Constraints

  • 1 ≤ n ≤ 3 * 10⁵
  • 1 ≤ executionTime[i] ≤ 10⁹
  • 1 ≤ y < x ≤ 10⁹

Example 1

Input:

executionTime = [3, 4, 1, 7, 6]
x = 4
y = 2

Output:

3

Explanation: The following strategy is optimal using 1-based indexing.

  • Choose job 4 as the major job and reduce the execution times of job 4 by x = 4 and of other jobs by y = 2. Now executionTime = [1, 2, -1, 3, 4]. Job 3 is complete, so it is removed.
  • Choose job 4, executionTime = [-1, 0, -, -1, 2]. So jobs 1, 2, and 4 are now complete :)
  • Choose job 5, executionTime = [-, -, -, -, -2]. Job 5 is complete. It takes 3 operations to execute all the jobs so the answer is 3.

Example 2

Input:

executionTime = [3, 3, 6, 3, 9]
x = 3
y = 2

Output:

3

Explanation:

  • Choose job 5, then executionTime = [1, 1, 4, 1, 6]. All jobs are still in the pool
  • Choose job 5, then executionTime = [-1, -1, 2, -1, 3]. So jobs 1,2 and 4 are complete.
  • Choose job 5, then executionTime = [-, -, 0, -, 0]. Jobs 3 and 5 are complete.

Example 3

Input:

executionTime = [2, 3, 5]
x = 3
y = 1

Output:

3

Explanation:

  • Choose job 3, then executionTime = [1, 2, 2]. All jobs are still in the pool
  • Choose job 3, then executionTime = [0, 1, -1]. So jobs 1 and 3 are complete.
  • Choose job 2, then executionTime = [-, -2, -]. Jobs 2 is complete.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Implement a prototype of a friend recommendation system for a social media application. There are n users indexed from 1 to n, and m friends represented as a 2d array, friendships, where the ith friendship is a connection between users friendships[i][0] and friendships[i][1]. User x is suggested as a friend to user y if x and y are not friends and have the maximum number of common friends, i.e. a friend of both x and y. If there are multiple possible such users x, the one with the minimum index is suggested. Given n and friendships, for each of the n users, find the index of the friend that should be recommended to them. If there is no recommendation available, report -1. Function Description Complete the function getRecommendedFriends in the editor. getRecommendedFriends has the following parameters:

  • int n: the number of users
  • int friendships[m][2]: the friendships between the users Returns int[]: an array of integers where the ith integer is the index of the recommended friend for the ith user, or -1 if no recommendation is available. Key insight: handle edge cases No friends, no friends of friends (This is so true irl ↕) ૮₍ ˶•⤙•˶ ₎ა All thanks go to Aura Man!𓇼 𓆡⋆.˚

Constraints

  • 1 ≤ n ≤ 10⁵
  • 0 ≤ m ≤ 2.5 x 10⁵
  • `0 ≤ friendships[i][0], friendships[i][1]

Example 1

Input:

n = 5
friendships = [[0, 1], [0, 2], [1, 3], [2, 3], [3, 4]]

Output:

[3, 2, 1, 0, 1]

Explanation:

Example 2

Input:

n = 3
friendships = [[0, 1], [1, 2], [2, 0]]

Output:

[-1, -1, -1]

Explanation:

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

The newspaper HackerRankNews distributed lottery tickets to everyone, and the winning lottery ID is described in the paper denoted by winnerID. In order to win the lottery, a customer having a lottery ID denoted by lotteryID needs to maximize the length of the longest common subsequence of the strings lotteryID and winnerID. To do so, the customer can perform up to k operations. In each operation, the customer can change any character in lotteryID either to its next or previous character. Find the maximum possible length of the longest common subsequence after at most k such operations. Note:

  • Operations can be performed only on lotteryID, not on winnerID.
  • The next character of a given character ch is the character that comes just after it in the alphabet. Similarly, the previous character is the character that comes just before it in the alphabet. For example, the next character of 'm' is 'n' and the previous is 'l'. For 'z' the next character is 'a' and for 'a' the previous character is 'z'.

Example 1

Input:

lotteryID = "fpeIqanxyk"
winnerID = "hackerrank"
k = 6

Output:

7

Explanation: The original explanation is not completed, I add my own understanding in the end for your reference. And also Output = 7 is calculated by me, it may not be accurate. It is just here for your refernce. Once I find more source, I will modify it immediately. One of the optimal ways to perform the operations is as follows:

  • Select i = 0, convert lotteryID[0] to its next character, lotteryID = "gpeIqanxyk"
  • Select i = 0, convert lotteryID[0] to its next character, lotteryID = "hpeIqanxyk"
  • Select i = 2, convert lotteryID[2] to its previous character, lotteryID = "hpdIqanxyk"
  • Select i = 2, convert lotteryID[2] to its previous character, lotteryID = "hpcIqanxyk" The maximum possible length of the longest common subsequence after at most k operations is 7.
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

You are given a binary tree and an integer targetSum. A valid path is a root-to-leaf path whose node values add up to targetSum. Among all valid paths, return the minimum one using the following tie-breaking rules:

  • Prefer the path with fewer nodes.
  • If lengths are equal, prefer the lexicographically smaller node-value sequence. If no valid path exists, return an empty array. Function Description Complete the function findMinimumTargetPath in the editor below. findMinimumTargetPath has the following parameters:
  • String[] levelOrder: the binary tree in level-order form, using "null" for missing children
  • int targetSum: the required path sum Returns int[]: the chosen root-to-leaf path, or an empty array if none exists.

Constraints

  • The input tree is finite and represented in level order.
  • The returned path must start at the root and end at a leaf.
  • If mult

Example 1

Input:

levelOrder = ["5", "4", "8", "11", "null", "13", "4", "7", "2", "null", "null", "5", "1"]
targetSum = 22

Output:

[5, 4, 11, 2]

Explanation: The path 5 -> 4 -> 11 -> 2 sums to 22 and is the selected valid path.

Example 2

Input:

levelOrder = ["1", "2", "3"]
targetSum = 5

Output:

[]

Explanation: No root-to-leaf path sums to 5, so the answer is empty.

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

Given a string s, return the number of palindromic substrings in it. A substring is palindromic if it reads the same forward and backward. (Same as LC 647.)

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters.

Example 1

Input:

s = "abc"

Output:

3

Explanation: Three palindromic strings: "a", "b", "c".

Example 2

Input:

s = "aaa"

Output:

6

Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁

There is a shop with old-style cash registers. Rather than scanning items and pulling the price from a database, the price of each item is typed in manually. This method sometimes leads to errors. Given a list of items and their correct prices, compare the prices to those entered when each item was sold. Determine the number of errors in selling prices. Function Description Complete the function priceCheck in the editor. priceCheck has the following parameter(s):

    1. String[] products: each products[i] is the name of an item for sale
    1. float[] productPrices: each productPrices[i] is the price of products[i]
    1. String[] productSold: each productSold[i] is the name of a product sold
    1. float[] soldPrice: each soldPrice[i] contains the sale price recorded for productSold[i] Returns int: the number of sale prices that were entered incorrectly

Constraints

  • 1 ≤ n ≤ m
  • 1 ≤ m ≤ n
  • |SP - productPrices[i], soldPrice[j]| ≤ 100000.00, where `0 ≤ i
Pro解法 · 三语代码 · 复杂度分析
边界讨论 + 面试官追问 · $98 / 一年解锁
Pro 会员

解锁全部 19 道题的解法

题面你已经看到了 — 解法 + 三语代码 + 复杂度推导 + 边界讨论, Pro 解锁.

Pro 解锁全部
  • 📚1000+ 道真实北美 OA, Python / Java / C++ 三语题解
  • 📊个人 dashboard + 进度可视化 + 14 天活跃图
  • 📝题目笔记跨设备同步 + 个人复盘库
  • 🔓随时取消下次续费, Stripe Customer Portal 自助管理
$12/月($98/年, 一次付清省 32%)

≈ 北美 SWE 工资 10 分钟 · LeetCode Premium $35/月 的 23%