Skip to content

Added tasks 3572-3579 #1993

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

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package g3501_3600.s3572_maximize_ysum_by_picking_a_triplet_of_distinct_xvalues;

// #Medium #2025_06_08_Time_51_ms_(100.00%)_Space_57.50_MB_(100.00%)

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class Solution {
public int maxSumDistinctTriplet(int[] x, int[] y) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < x.length; i++) {
map.put(x[i], Math.max(map.getOrDefault(x[i], 0), y[i]));
}
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());
for (int val : map.values()) {
maxHeap.add(val);
}
if (maxHeap.size() < 3) {
return -1;
}
int sum = 0;
for (int i = 0; i < 3; i++) {
sum += maxHeap.poll();
}
return sum;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
3572\. Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values

Medium

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:

* `x[i] != x[j]`
* `x[j] != x[k]`
* `x[k] != x[i]`

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.

If no such triplet exists, return -1.

**Example 1:**

**Input:** x = [1,2,1,3,2], y = [5,3,4,6,2]

**Output:** 14

**Explanation:**

* 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`).
* All three values chosen from `x` are distinct. `5 + 3 + 6 = 14` is the maximum we can obtain. Hence, the output is 14.

**Example 2:**

**Input:** x = [1,2,1,2], y = [4,5,6,7]

**Output:** \-1

**Explanation:**

* There are only two distinct values in `x`. Hence, the output is -1.

**Constraints:**

* `n == x.length == y.length`
* <code>3 <= n <= 10<sup>5</sup></code>
* <code>1 <= x[i], y[i] <= 10<sup>6</sup></code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package g3501_3600.s3573_best_time_to_buy_and_sell_stock_v;

// #Medium #2025_06_08_Time_259_ms_(100.00%)_Space_87.72_MB_(100.00%)

import java.util.Arrays;

public class Solution {
private static final long MN = (long) -1e14;
private long[][][] dp;
private int[] prices;

private long f(int i, int k, int state) {
if (i == prices.length) {
return (state == 0) ? 0 : MN;
}
if (dp[i][k][state] != MN) {
return dp[i][k][state];
}
long p = prices[i];
long profit = MN;
profit = Math.max(profit, f(i + 1, k, state));
if (state == 0) {
profit = Math.max(profit, f(i + 1, k, 1) - p);
profit = Math.max(profit, f(i + 1, k, 2) + p);
} else if (k > 0) {
if (state == 1) {
profit = Math.max(profit, f(i + 1, k - 1, 0) + p);
} else {
profit = Math.max(profit, f(i + 1, k - 1, 0) - p);
}
}
dp[i][k][state] = profit;
return profit;
}

public long maximumProfit(int[] prices, int k) {
this.prices = prices;
int n = prices.length;
dp = new long[n + 1][k + 1][3];
for (long[][] twoD : dp) {
for (long[] oneD : twoD) {
Arrays.fill(oneD, MN);
}
}
return f(0, k, 0);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
3573\. Best Time to Buy and Sell Stock V

Medium

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`.

You are allowed to make at most `k` transactions, where each transaction can be either of the following:

* **Normal transaction**: Buy on day `i`, then sell on a later day `j` where `i < j`. You profit `prices[j] - prices[i]`.

* **Short selling transaction**: Sell on day `i`, then buy back on a later day `j` where `i < j`. You profit `prices[i] - prices[j]`.


**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.

Return the **maximum** total profit you can earn by making **at most** `k` transactions.

**Example 1:**

**Input:** prices = [1,7,9,8,2], k = 2

**Output:** 14

**Explanation:**

We can make $14 of profit through 2 transactions:

* A normal transaction: buy the stock on day 0 for $1 then sell it on day 2 for $9.
* A short selling transaction: sell the stock on day 3 for $8 then buy back on day 4 for $2.

**Example 2:**

**Input:** prices = [12,16,19,19,8,1,19,13,9], k = 3

**Output:** 36

**Explanation:**

We can make $36 of profit through 3 transactions:

* A normal transaction: buy the stock on day 0 for $12 then sell it on day 2 for $19.
* A short selling transaction: sell the stock on day 3 for $19 then buy back on day 4 for $8.
* A normal transaction: buy the stock on day 5 for $1 then sell it on day 6 for $19.

**Constraints:**

* <code>2 <= prices.length <= 10<sup>3</sup></code>
* <code>1 <= prices[i] <= 10<sup>9</sup></code>
* `1 <= k <= prices.length / 2`
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package g3501_3600.s3574_maximize_subarray_gcd_score;

// #Hard #2025_06_08_Time_364_ms_(100.00%)_Space_44.70_MB_(100.00%)

public class Solution {
public long maxGCDScore(int[] nums, int k) {
long ans = 0;
int n = nums.length;
for (int i = 0; i < n; i++) {
long countGCD = 0;
long oddCount = 0;
long ongoingGCD = 0;
for (int j = i; j < n; j++) {
long currentGCD = gcd(ongoingGCD, nums[j]);
if (currentGCD != ongoingGCD) {
ongoingGCD = currentGCD;
countGCD = 1;
} else if (nums[j] == ongoingGCD) {
countGCD++;
}
if (nums[j] % 2 != 0) {
oddCount++;
}
int len = j - i + 1;
long res = ongoingGCD * len;
if (ongoingGCD % 2 != 0) {
if (k >= oddCount) {
res *= 2L;
}
} else if (k >= countGCD) {
res *= 2L;
}
ans = Math.max(ans, res);
}
}
return ans;
}

private long gcd(long a, long b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
3574\. Maximize Subarray GCD Score

Hard

You are given an array of positive integers `nums` and an integer `k`.

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.

The **score** of a contiguous **subarray** is defined as the **product** of its length and the _greatest common divisor (GCD)_ of all its elements.

Your task is to return the **maximum** **score** that can be achieved by selecting a contiguous subarray from the modified array.

**Note:**

* The **greatest common divisor (GCD)** of an array is the largest integer that evenly divides all the array elements.

**Example 1:**

**Input:** nums = [2,4], k = 1

**Output:** 8

**Explanation:**

* Double `nums[0]` to 4 using one operation. The modified array becomes `[4, 4]`.
* The GCD of the subarray `[4, 4]` is 4, and the length is 2.
* Thus, the maximum possible score is `2 × 4 = 8`.

**Example 2:**

**Input:** nums = [3,5,7], k = 2

**Output:** 14

**Explanation:**

* Double `nums[2]` to 14 using one operation. The modified array becomes `[3, 5, 14]`.
* The GCD of the subarray `[14]` is 14, and the length is 1.
* Thus, the maximum possible score is `1 × 14 = 14`.

**Example 3:**

**Input:** nums = [5,5,5], k = 1

**Output:** 15

**Explanation:**

* The subarray `[5, 5, 5]` has a GCD of 5, and its length is 3.
* Since doubling any element doesn't improve the score, the maximum score is `3 × 5 = 15`.

**Constraints:**

* `1 <= n == nums.length <= 1500`
* <code>1 <= nums[i] <= 10<sup>9</sup></code>
* `1 <= k <= n`
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package g3501_3600.s3575_maximum_good_subtree_score;

// #Hard #2025_06_08_Time_564_ms_(100.00%)_Space_45.22_MB_(100.00%)

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@SuppressWarnings("unchecked")
public class Solution {
private long ans;
private static final int MOD = 1_000_000_007;

public int goodSubtreeSum(int[] vals, int[] par) {
int n = vals.length;
List<Integer>[] adj = new ArrayList[n];
for (int i = 0; i < n; i++) {
adj[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
adj[par[i]].add(i);
}
this.ans = 0;
dfs(0, vals, adj);
return (int) ((this.ans % MOD + MOD) % MOD);
}

private Map<Integer, Integer> dfs(int u, int[] vals, List<Integer>[] adj) {
// du: The DP map for the subtree at node u.
// Key: bitmask of digits. Value: max sum for that combination of digits.
Map<Integer, Integer> du = new HashMap<>();
// Base case: A sum of 0 is possible with an empty set of digits (mask 0).
du.put(0, 0);
// Process the current node's value.
String s = String.valueOf(Math.abs(vals[u]));
if (hasUniqueDigits(s)) {
int mask = 0;
for (char c : s.toCharArray()) {
mask |= (1 << (c - '0'));
}
du.put(mask, vals[u]);
}
for (int v : adj[u]) {
Map<Integer, Integer> dv = dfs(v, vals, adj);
Map<Integer, Integer> duSnapshot = new HashMap<>(du);
for (Map.Entry<Integer, Integer> entryV : dv.entrySet()) {
int mv = entryV.getKey();
int sv = entryV.getValue();
for (Map.Entry<Integer, Integer> entryU : duSnapshot.entrySet()) {
int mu = entryU.getKey();
int su = entryU.getValue();
// If the digit sets are disjoint (no common bits in masks), we can combine
// them.
if ((mu & mv) == 0) {
int newMask = mu | mv;
int newSum = su + sv;
// Update `du` with the best possible sum for the new combined mask.
du.put(
newMask,
Math.max(du.getOrDefault(newMask, Integer.MIN_VALUE), newSum));
}
}
}
}
// After processing all children, the max value in `du` is the "good" sum for the subtree at
// u.
// Initialize with a very small number to correctly find the maximum, even if sums are
// negative.
int maxSubtreeSum = Integer.MIN_VALUE;
for (int sum : du.values()) {
maxSubtreeSum = Math.max(maxSubtreeSum, sum);
}
// Add this subtree's best sum to the total answer.
// If du is empty (should not happen due to {0:0}), we add 0.
this.ans += (maxSubtreeSum == Integer.MIN_VALUE ? 0 : maxSubtreeSum);
return du;
}

private boolean hasUniqueDigits(String s) {
Set<Character> digits = new HashSet<>();
for (char c : s.toCharArray()) {
if (!digits.add(c)) {
return false;
}
}
return true;
}
}
Loading