Skip to content

Commit e0edca5

Browse files
committed
Added tasks 3572-3579
1 parent 014368f commit e0edca5

File tree

24 files changed

+988
-0
lines changed

24 files changed

+988
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package g3501_3600.s3572_maximize_ysum_by_picking_a_triplet_of_distinct_xvalues;
2+
3+
// #Medium #2025_06_08_Time_51_ms_(100.00%)_Space_57.50_MB_(100.00%)
4+
5+
import java.util.Collections;
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
import java.util.PriorityQueue;
9+
10+
public class Solution {
11+
public int maxSumDistinctTriplet(int[] x, int[] y) {
12+
Map<Integer, Integer> map = new HashMap<>();
13+
for (int i = 0; i < x.length; i++) {
14+
map.put(x[i], Math.max(map.getOrDefault(x[i], 0), y[i]));
15+
}
16+
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
17+
for (int val : map.values()) {
18+
maxHeap.add(val);
19+
}
20+
if (maxHeap.size() < 3) {
21+
return -1;
22+
}
23+
int sum = 0;
24+
for (int i = 0; i < 3; i++) {
25+
sum += maxHeap.poll();
26+
}
27+
return sum;
28+
}
29+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
3572\. Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
2+
3+
Medium
4+
5+
You are given two integer arrays `x` and `y`, each of length `n`. You must choose three **distinct** indices `i`, `j`, and `k` such that:
6+
7+
* `x[i] != x[j]`
8+
* `x[j] != x[k]`
9+
* `x[k] != x[i]`
10+
11+
Your goal is to **maximize** the value of `y[i] + y[j] + y[k]` under these conditions. Return the **maximum** possible sum that can be obtained by choosing such a triplet of indices.
12+
13+
If no such triplet exists, return -1.
14+
15+
**Example 1:**
16+
17+
**Input:** x = [1,2,1,3,2], y = [5,3,4,6,2]
18+
19+
**Output:** 14
20+
21+
**Explanation:**
22+
23+
* Choose `i = 0` (`x[i] = 1`, `y[i] = 5`), `j = 1` (`x[j] = 2`, `y[j] = 3`), `k = 3` (`x[k] = 3`, `y[k] = 6`).
24+
* All three values chosen from `x` are distinct. `5 + 3 + 6 = 14` is the maximum we can obtain. Hence, the output is 14.
25+
26+
**Example 2:**
27+
28+
**Input:** x = [1,2,1,2], y = [4,5,6,7]
29+
30+
**Output:** \-1
31+
32+
**Explanation:**
33+
34+
* There are only two distinct values in `x`. Hence, the output is -1.
35+
36+
**Constraints:**
37+
38+
* `n == x.length == y.length`
39+
* <code>3 <= n <= 10<sup>5</sup></code>
40+
* <code>1 <= x[i], y[i] <= 10<sup>6</sup></code>
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package g3501_3600.s3573_best_time_to_buy_and_sell_stock_v;
2+
3+
// #Medium #2025_06_08_Time_259_ms_(100.00%)_Space_87.72_MB_(100.00%)
4+
5+
import java.util.Arrays;
6+
7+
public class Solution {
8+
private static final long MN = (long) -1e14;
9+
private long[][][] dp;
10+
private int[] prices;
11+
12+
private long f(int i, int k, int state) {
13+
if (i == prices.length) {
14+
return (state == 0) ? 0 : MN;
15+
}
16+
if (dp[i][k][state] != MN) {
17+
return dp[i][k][state];
18+
}
19+
long p = prices[i];
20+
long profit = MN;
21+
profit = Math.max(profit, f(i + 1, k, state));
22+
if (state == 0) {
23+
profit = Math.max(profit, f(i + 1, k, 1) - p);
24+
profit = Math.max(profit, f(i + 1, k, 2) + p);
25+
} else if (k > 0) {
26+
if (state == 1) {
27+
profit = Math.max(profit, f(i + 1, k - 1, 0) + p);
28+
} else {
29+
profit = Math.max(profit, f(i + 1, k - 1, 0) - p);
30+
}
31+
}
32+
return dp[i][k][state] = profit;
33+
}
34+
35+
public long maximumProfit(int[] prices, int k) {
36+
this.prices = prices;
37+
int n = prices.length;
38+
dp = new long[n + 1][k + 1][3];
39+
for (long[][] twoD : dp) {
40+
for (long[] oneD : twoD) {
41+
Arrays.fill(oneD, MN);
42+
}
43+
}
44+
return f(0, k, 0);
45+
}
46+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
3573\. Best Time to Buy and Sell Stock V
2+
3+
Medium
4+
5+
You are given an integer array `prices` where `prices[i]` is the price of a stock in dollars on the <code>i<sup>th</sup></code> day, and an integer `k`.
6+
7+
You are allowed to make at most `k` transactions, where each transaction can be either of the following:
8+
9+
* **Normal transaction**: Buy on day `i`, then sell on a later day `j` where `i < j`. You profit `prices[j] - prices[i]`.
10+
11+
* **Short selling transaction**: Sell on day `i`, then buy back on a later day `j` where `i < j`. You profit `prices[i] - prices[j]`.
12+
13+
14+
**Note** that you must complete each transaction before starting another. Additionally, you can't buy or sell on the same day you are selling or buying back as part of a previous transaction.
15+
16+
Return the **maximum** total profit you can earn by making **at most** `k` transactions.
17+
18+
**Example 1:**
19+
20+
**Input:** prices = [1,7,9,8,2], k = 2
21+
22+
**Output:** 14
23+
24+
**Explanation:**
25+
26+
We can make $14 of profit through 2 transactions:
27+
28+
* A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.
29+
* A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.
30+
31+
**Example 2:**
32+
33+
**Input:** prices = [12,16,19,19,8,1,19,13,9], k = 3
34+
35+
**Output:** 36
36+
37+
**Explanation:**
38+
39+
We can make $36 of profit through 3 transactions:
40+
41+
* A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.
42+
* A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.
43+
* A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.
44+
45+
**Constraints:**
46+
47+
* <code>2 <= prices.length <= 10<sup>3</sup></code>
48+
* <code>1 <= prices[i] <= 10<sup>9</sup></code>
49+
* `1 <= k <= prices.length / 2`
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package g3501_3600.s3574_maximize_subarray_gcd_score;
2+
3+
// #Hard #2025_06_08_Time_364_ms_(100.00%)_Space_44.70_MB_(100.00%)
4+
5+
public class Solution {
6+
public long maxGCDScore(int[] nums, int k) {
7+
long ans = 0;
8+
int n = nums.length;
9+
for (int i = 0; i < n; i++) {
10+
long countGCD = 0;
11+
long oddCount = 0;
12+
long ongoingGCD = 0;
13+
for (int j = i; j < n; j++) {
14+
long currentGCD = gcd(ongoingGCD, nums[j]);
15+
if (currentGCD != ongoingGCD) {
16+
ongoingGCD = currentGCD;
17+
countGCD = 1;
18+
} else if (nums[j] == ongoingGCD) {
19+
countGCD++;
20+
}
21+
if (nums[j] % 2 != 0) {
22+
oddCount++;
23+
}
24+
int len = j - i + 1;
25+
long res = ongoingGCD * len;
26+
if (ongoingGCD % 2 != 0) {
27+
if (k >= oddCount) {
28+
res *= 2L;
29+
}
30+
} else if (k >= countGCD) {
31+
res *= 2L;
32+
}
33+
ans = Math.max(ans, res);
34+
}
35+
}
36+
return ans;
37+
}
38+
39+
private long gcd(long a, long b) {
40+
if (a == 0) {
41+
return b;
42+
}
43+
return gcd(b % a, a);
44+
}
45+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
3574\. Maximize Subarray GCD Score
2+
3+
Hard
4+
5+
You are given an array of positive integers `nums` and an integer `k`.
6+
7+
You may perform at most `k` operations. In each operation, you can choose one element in the array and **double** its value. Each element can be doubled **at most** once.
8+
9+
The **score** of a contiguous **subarray** is defined as the **product** of its length and the _greatest common divisor (GCD)_ of all its elements.
10+
11+
Your task is to return the **maximum** **score** that can be achieved by selecting a contiguous subarray from the modified array.
12+
13+
**Note:**
14+
15+
* The **greatest common divisor (GCD)** of an array is the largest integer that evenly divides all the array elements.
16+
17+
**Example 1:**
18+
19+
**Input:** nums = [2,4], k = 1
20+
21+
**Output:** 8
22+
23+
**Explanation:**
24+
25+
* Double `nums[0]` to 4 using one operation. The modified array becomes `[4, 4]`.
26+
* The GCD of the subarray `[4, 4]` is 4, and the length is 2.
27+
* Thus, the maximum possible score is `2 × 4 = 8`.
28+
29+
**Example 2:**
30+
31+
**Input:** nums = [3,5,7], k = 2
32+
33+
**Output:** 14
34+
35+
**Explanation:**
36+
37+
* Double `nums[2]` to 14 using one operation. The modified array becomes `[3, 5, 14]`.
38+
* The GCD of the subarray `[14]` is 14, and the length is 1.
39+
* Thus, the maximum possible score is `1 × 14 = 14`.
40+
41+
**Example 3:**
42+
43+
**Input:** nums = [5,5,5], k = 1
44+
45+
**Output:** 15
46+
47+
**Explanation:**
48+
49+
* The subarray `[5, 5, 5]` has a GCD of 5, and its length is 3.
50+
* Since doubling any element doesn't improve the score, the maximum score is `3 × 5 = 15`.
51+
52+
**Constraints:**
53+
54+
* `1 <= n == nums.length <= 1500`
55+
* <code>1 <= nums[i] <= 10<sup>9</sup></code>
56+
* `1 <= k <= n`
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package g3501_3600.s3575_maximum_good_subtree_score;
2+
3+
// #Hard #2025_06_08_Time_564_ms_(100.00%)_Space_45.22_MB_(100.00%)
4+
5+
import java.util.ArrayList;
6+
import java.util.HashMap;
7+
import java.util.HashSet;
8+
import java.util.List;
9+
import java.util.Map;
10+
import java.util.Set;
11+
12+
@SuppressWarnings("unchecked")
13+
public class Solution {
14+
private long ans;
15+
private static final int MOD = 1_000_000_007;
16+
17+
public int goodSubtreeSum(int[] vals, int[] par) {
18+
int n = vals.length;
19+
List<Integer>[] adj = new ArrayList[n];
20+
for (int i = 0; i < n; i++) {
21+
adj[i] = new ArrayList<>();
22+
}
23+
for (int i = 1; i < n; i++) {
24+
adj[par[i]].add(i);
25+
}
26+
this.ans = 0;
27+
dfs(0, vals, adj);
28+
return (int) ((this.ans % MOD + MOD) % MOD);
29+
}
30+
31+
private Map<Integer, Integer> dfs(int u, int[] vals, List<Integer>[] adj) {
32+
// du: The DP map for the subtree at node u.
33+
// Key: bitmask of digits. Value: max sum for that combination of digits.
34+
Map<Integer, Integer> du = new HashMap<>();
35+
// Base case: A sum of 0 is possible with an empty set of digits (mask 0).
36+
du.put(0, 0);
37+
// Process the current node's value.
38+
String s = String.valueOf(Math.abs(vals[u]));
39+
if (hasUniqueDigits(s)) {
40+
int mask = 0;
41+
for (char c : s.toCharArray()) {
42+
mask |= (1 << (c - '0'));
43+
}
44+
du.put(mask, vals[u]);
45+
}
46+
for (int v : adj[u]) {
47+
Map<Integer, Integer> dv = dfs(v, vals, adj);
48+
Map<Integer, Integer> duSnapshot = new HashMap<>(du);
49+
for (Map.Entry<Integer, Integer> entryV : dv.entrySet()) {
50+
int mv = entryV.getKey();
51+
int sv = entryV.getValue();
52+
for (Map.Entry<Integer, Integer> entryU : duSnapshot.entrySet()) {
53+
int mu = entryU.getKey();
54+
int su = entryU.getValue();
55+
// If the digit sets are disjoint (no common bits in masks), we can combine
56+
// them.
57+
if ((mu & mv) == 0) {
58+
int newMask = mu | mv;
59+
int newSum = su + sv;
60+
// Update `du` with the best possible sum for the new combined mask.
61+
du.put(
62+
newMask,
63+
Math.max(du.getOrDefault(newMask, Integer.MIN_VALUE), newSum));
64+
}
65+
}
66+
}
67+
}
68+
// After processing all children, the max value in `du` is the "good" sum for the subtree at
69+
// u.
70+
// Initialize with a very small number to correctly find the maximum, even if sums are
71+
// negative.
72+
int maxSubtreeSum = Integer.MIN_VALUE;
73+
for (int sum : du.values()) {
74+
maxSubtreeSum = Math.max(maxSubtreeSum, sum);
75+
}
76+
// Add this subtree's best sum to the total answer.
77+
// If du is empty (should not happen due to {0:0}), we add 0.
78+
this.ans += (maxSubtreeSum == Integer.MIN_VALUE ? 0 : maxSubtreeSum);
79+
return du;
80+
}
81+
82+
private boolean hasUniqueDigits(String s) {
83+
Set<Character> digits = new HashSet<>();
84+
for (char c : s.toCharArray()) {
85+
if (!digits.add(c)) {
86+
return false;
87+
}
88+
}
89+
return true;
90+
}
91+
}

0 commit comments

Comments
 (0)