Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revised Solution #3283

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
27 changes: 16 additions & 11 deletions solution/0800-0899/0878.Nth Magical Number/Solution.java
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
class Solution {
private static final int MOD = (int) 1e9 + 7;

public int nthMagicalNumber(int n, int a, int b) {
int c = a * b / gcd(a, b);
long l = 0, r = (long) (a + b) * n;
while (l < r) {
long mid = l + r >>> 1;
if (mid / a + mid / b - mid / c >= n) {
r = mid;
long lcm = lcm(a, b);
long ans = 0;
// binary search
for (long l = 0, r = (long) n * Math.min(a, b), m = 0; l <= r;) {
m = (l + r) / 2;
if (m / a + m / b - m /lcm >= n) {
ans = m;
r = m - 1;
} else {
l = mid + 1;
l = m + 1;
}
}
return (int) (l % MOD);
return (int) (ans % 1000000007);
}

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

public static long lcm(long a, long b) {
return (long) a / gcd(a, b) * b;
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,32 @@
class Solution:
def numSubmatrixSumTarget(self, matrix: List[List[int]], target: int) -> int:
def f(nums: List[int]) -> int:
d = defaultdict(int)
d[0] = 1
cnt = s = 0
for x in nums:
s += x
cnt += d[s - target]
d[s] += 1
return cnt
def numSubmatrixSumTarget(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: int
"""
m = len(matrix)
n = len(matrix[0])
ans = 0
for i in range(m):
col = [0] * n
for j in range(i, m):
for k in range(n):
col[k] += matrix[j][k]
ans += self.f(col, target)
return ans

m, n = len(matrix), len(matrix[0])
ans = 0
for i in range(m):
col = [0] * n
for j in range(i, m):
for k in range(n):
col[k] += matrix[j][k]
ans += f(col)
return ans
def f(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
d = {0: 1} # map to store prefix sum counts
s = 0
cnt = 0
for x in nums:
s += x
cnt += d.get(s - target, 0) # count subarray sums equal to target
d[s] = d.get(s, 0) + 1 # update prefix sum count
return cnt
42 changes: 21 additions & 21 deletions solution/1200-1299/1224.Maximum Equal Frequency/Solution.java
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
class Solution {
private static int[] cnt = new int[100010];
private static int[] ccnt = new int[100010];
import java.util.HashMap;
import java.util.Map;

class Solution {
public int maxEqualFreq(int[] nums) {
Arrays.fill(cnt, 0);
Arrays.fill(ccnt, 0);
int ans = 0;
int mx = 0;
for (int i = 1; i <= nums.length; ++i) {
int v = nums[i - 1];
if (cnt[v] > 0) {
--ccnt[cnt[v]];
Map<Integer, Integer> count = new HashMap<>(); // Use HashMap to store the frequency of each number
Map<Integer, Integer> freqCount = new HashMap<>(); // Use HashMap to store the frequency of each frequency
int maxFreq = 0, ans = 0;
for (int i = 0; i < nums.length; i++) {
int num = nums[i];
if (count.containsKey(num)) {
freqCount.put(count.get(num), freqCount.getOrDefault(count.get(num), 0) - 1); // Decrement the count of the previous frequency
}
++cnt[v];
mx = Math.max(mx, cnt[v]);
++ccnt[cnt[v]];
if (mx == 1) {
ans = i;
} else if (ccnt[mx] * mx + ccnt[mx - 1] * (mx - 1) == i && ccnt[mx] == 1) {
ans = i;
} else if (ccnt[mx] * mx + 1 == i && ccnt[1] == 1) {
ans = i;
count.put(num, count.getOrDefault(num, 0) + 1); // Increment the count of the current number
maxFreq = Math.max(maxFreq, count.get(num)); // Update the maximum frequency
freqCount.put(count.get(num), freqCount.getOrDefault(count.get(num), 0) + 1); // Increment the count of the current frequency

if (maxFreq == 1) {
ans = i + 1; // Update the answer if all elements have the same frequency (1)
} else if (freqCount.get(maxFreq) * maxFreq + (freqCount.getOrDefault(maxFreq - 1, 0) * (maxFreq - 1)) == i + 1 && freqCount.get(maxFreq) == 1) {
ans = i + 1; // Update the answer if there's only one element with the maximum frequency and all other elements have a frequency one less than the maximum
} else if (freqCount.get(maxFreq) * maxFreq + 1 == i + 1 && freqCount.get(1) == 1) {
ans = i + 1; // Update the answer if there's only one element with a frequency of 1 and all other elements have the maximum frequency
}
}
return ans;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,30 +1,31 @@
class Solution {
public int maxValueAfterReverse(int[] nums) {
int n = nums.length;
int s = 0;
for (int i = 0; i < n - 1; ++i) {
s += Math.abs(nums[i] - nums[i + 1]);
}
int ans = s;
for (int i = 0; i < n - 1; ++i) {
ans = Math.max(
ans, s + Math.abs(nums[0] - nums[i + 1]) - Math.abs(nums[i] - nums[i + 1]));
ans = Math.max(
ans, s + Math.abs(nums[n - 1] - nums[i]) - Math.abs(nums[i] - nums[i + 1]));
}
int[] dirs = {1, -1, -1, 1, 1};
final int inf = 1 << 30;
for (int k = 0; k < 4; ++k) {
int k1 = dirs[k], k2 = dirs[k + 1];
int mx = -inf, mi = inf;
for (int i = 0; i < n - 1; ++i) {
int a = k1 * nums[i] + k2 * nums[i + 1];
int b = Math.abs(nums[i] - nums[i + 1]);
mx = Math.max(mx, a - b);
mi = Math.min(mi, a + b);
}
ans = Math.max(ans, s + Math.max(0, mx - mi));
}
return ans;

public int maxValueAfterReverse(int[] nums) {
int n = nums.length;
int s = 0;
for (int i = 0; i < n - 1; ++i) {
s += Math.abs(nums[i] - nums[i + 1]);
}
}
int ans = s;
for (int i = 0; i < n - 1; ++i) {
ans = Math.max(
ans, s + Math.abs(nums[0] - nums[i + 1]) - Math.abs(nums[i] - nums[i + 1]));
ans = Math.max(
ans, s + Math.abs(nums[n - 1] - nums[i]) - Math.abs(nums[i] - nums[i + 1]));
}
int[] dirs = {1, -1, -1, 1, 1};
final int inf = 1 << 30;
for (int k = 0; k < 4; ++k) {
int k1 = dirs[k], k2 = dirs[k + 1];
int mx = -inf, mi = inf;
for (int i = 0; i < n - 1; ++i) {
int a = k1 * nums[i] + k2 * nums[i + 1];
int b = Math.abs(nums[i] - nums[i + 1]);
mx = Math.max(mx, a - b);
mi = Math.min(mi, a + b);
}
ans = Math.max(ans, s + Math.max(0, mx - mi));
}
return ans;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import java.util.*;

public class Solution {
private Map<List<Integer>, int[]> memo = new HashMap<>();

public int[] earliestAndLatest(int n, int firstPlayer, int secondPlayer) {
return dp(firstPlayer, n - secondPlayer + 1, n);
}

private int[] dp(int l, int r, int k) {
if (l == r) return new int[]{1, 1};
if (l > r) return dp(r, l, k);

List<Integer> key = Arrays.asList(l, r, k);
if (memo.containsKey(key)) return memo.get(key);

int earliest = Integer.MAX_VALUE;
int latest = Integer.MIN_VALUE;

// Enumerate all possible positions
for (int i = 1; i <= l; ++i) {
for (int j = l - i + 1; j <= r - i + 1; ++j) {
if (!(l + r - k / 2 <= i + j && i + j <= (k + 1) / 2)) continue;

int[] result = dp(i, j, (k + 1) / 2);
earliest = Math.min(earliest, result[0] + 1);
latest = Math.max(latest, result[1] + 1);
}
}

int[] result = new int[]{earliest, latest};
memo.put(key, result);
return result;
}
}
116 changes: 116 additions & 0 deletions solution/1900-1999/1938.Maximum Genetic Difference Query/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import java.util.*;

class TrieNode {
TrieNode[] children;
int count;

public TrieNode() {
this.children = new TrieNode[2];
this.count = 0;
}
}

class Trie {
private final TrieNode root;

public Trie() {
this.root = new TrieNode();
}

public void insert(int num) {
TrieNode node = root;
for (int i = 17; i >= 0; i--) {
int bit = (num >> i) & 1;
if (node.children[bit] == null) {
node.children[bit] = new TrieNode();
}
node = node.children[bit];
node.count++;
}
}

public void remove(int num) {
TrieNode node = root;
for (int i = 17; i >= 0; i--) {
int bit = (num >> i) & 1;
node = node.children[bit];
node.count--;
}
}

public int maxXOR(int num) {
TrieNode node = root;
int max_xor = 0;
for (int i = 17; i >= 0; i--) {
int bit = (num >> i) & 1;
int toggled_bit = 1 - bit;
if (node.children[toggled_bit] != null && node.children[toggled_bit].count > 0) {
max_xor |= (1 << i);
node = node.children[toggled_bit];
} else {
node = node.children[bit];
}
}
return max_xor;
}
}

class Solution {
public int[] maxGeneticDifference(int[] parents, int[][] queries) {
int n = parents.length;

// Build the tree as an adjacency list
Map<Integer, List<Integer>> tree = new HashMap<>();
int root = -1;

for (int i = 0; i < n; i++) {
if (parents[i] == -1) {
root = i;
} else {
tree.computeIfAbsent(parents[i], k -> new ArrayList<>()).add(i);
}
}

// Group queries by node
Map<Integer, List<int[]>> queryMap = new HashMap<>();
for (int i = 0; i < queries.length; i++) {
int node = queries[i][0];
int val = queries[i][1];
queryMap.computeIfAbsent(node, k -> new ArrayList<>()).add(new int[]{val, i});
}

// Result array
int[] res = new int[queries.length];

// Trie to store and query the path genetic values
Trie trie = new Trie();

// Depth-first search to solve the queries
dfs(root, tree, queryMap, trie, res);

return res;
}

private void dfs(int node, Map<Integer, List<Integer>> tree, Map<Integer, List<int[]>> queryMap, Trie trie, int[] res) {
trie.insert(node);

// Handle queries for this node
if (queryMap.containsKey(node)) {
for (int[] query : queryMap.get(node)) {
int val = query[0];
int idx = query[1];
res[idx] = trie.maxXOR(val);
}
}

// Recurse for children
if (tree.containsKey(node)) {
for (int child : tree.get(node)) {
dfs(child, tree, queryMap, trie, res);
}
}

// Remove the node after processing its subtree
trie.remove(node);
}
}
Loading
Loading