Skip to content

Commit 666ef69

Browse files
committed
Added tasks 3572-3579
1 parent 1d3dc23 commit 666ef69

File tree

24 files changed

+1042
-0
lines changed

24 files changed

+1042
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package g3501_3600.s3572_maximize_ysum_by_picking_a_triplet_of_distinct_xvalues
2+
3+
// #Medium #2025_06_08_Time_72_ms_(100.00%)_Space_77.69_MB_(100.00%)
4+
5+
import java.util.Collections
6+
import java.util.PriorityQueue
7+
import kotlin.math.max
8+
9+
class Solution {
10+
fun maxSumDistinctTriplet(x: IntArray, y: IntArray): Int {
11+
val map: MutableMap<Int, Int> = HashMap<Int, Int>()
12+
for (i in x.indices) {
13+
map.put(x[i], max(map.getOrDefault(x[i], 0), y[i]))
14+
}
15+
val maxHeap = PriorityQueue<Int>(Collections.reverseOrder<Int>())
16+
for (`val` in map.values) {
17+
maxHeap.add(`val`)
18+
}
19+
if (maxHeap.size < 3) {
20+
return -1
21+
}
22+
var sum = 0
23+
for (i in 0..2) {
24+
sum += maxHeap.poll()!!
25+
}
26+
return sum
27+
}
28+
}
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: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package g3501_3600.s3573_best_time_to_buy_and_sell_stock_v
2+
3+
// #Medium #2025_06_08_Time_157_ms_(100.00%)_Space_99.08_MB_(100.00%)
4+
5+
import kotlin.math.max
6+
7+
class Solution {
8+
private lateinit var dp: Array<Array<LongArray>>
9+
private lateinit var prices: IntArray
10+
11+
private fun f(i: Int, k: Int, state: Int): Long {
12+
if (i == prices.size) {
13+
return if (state == 0) 0 else MN
14+
}
15+
if (dp[i][k][state] != MN) {
16+
return dp[i][k][state]
17+
}
18+
val p = prices[i].toLong()
19+
var profit: Long = MN
20+
profit = max(profit, f(i + 1, k, state))
21+
if (state == 0) {
22+
profit = max(profit, f(i + 1, k, 1) - p)
23+
profit = max(profit, f(i + 1, k, 2) + p)
24+
} else if (k > 0) {
25+
profit = if (state == 1) {
26+
max(profit, f(i + 1, k - 1, 0) + p)
27+
} else {
28+
max(profit, f(i + 1, k - 1, 0) - p)
29+
}
30+
}
31+
dp[i][k][state] = profit
32+
return profit
33+
}
34+
35+
fun maximumProfit(prices: IntArray, k: Int): Long {
36+
this.prices = prices
37+
val n = prices.size
38+
dp = Array<Array<LongArray>>(n + 1) { Array<LongArray>(k + 1) { LongArray(3) } }
39+
for (twoD in dp) {
40+
for (oneD in twoD) {
41+
oneD.fill(MN)
42+
}
43+
}
44+
return f(0, k, 0)
45+
}
46+
47+
companion object {
48+
private val MN = -1e14.toLong()
49+
}
50+
}
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: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package g3501_3600.s3574_maximize_subarray_gcd_score
2+
3+
// #Hard #2025_06_08_Time_269_ms_(100.00%)_Space_63.86_MB_(100.00%)
4+
5+
import kotlin.math.max
6+
7+
class Solution {
8+
fun maxGCDScore(nums: IntArray, k: Int): Long {
9+
var ans: Long = 0
10+
val n = nums.size
11+
for (i in 0..<n) {
12+
var countGCD: Long = 0
13+
var oddCount: Long = 0
14+
var ongoingGCD: Long = 0
15+
for (j in i..<n) {
16+
val currentGCD = gcd(ongoingGCD, nums[j].toLong())
17+
if (currentGCD != ongoingGCD) {
18+
ongoingGCD = currentGCD
19+
countGCD = 1
20+
} else if (nums[j].toLong() == ongoingGCD) {
21+
countGCD++
22+
}
23+
if (nums[j] % 2 != 0) {
24+
oddCount++
25+
}
26+
val len = j - i + 1
27+
var res = ongoingGCD * len
28+
if (ongoingGCD % 2 != 0L) {
29+
if (k >= oddCount) {
30+
res *= 2L
31+
}
32+
} else if (k >= countGCD) {
33+
res *= 2L
34+
}
35+
ans = max(ans, res)
36+
}
37+
}
38+
return ans
39+
}
40+
41+
private fun gcd(a: Long, b: Long): Long {
42+
if (a == 0L) {
43+
return b
44+
}
45+
return gcd(b % a, a)
46+
}
47+
}
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: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package g3501_3600.s3575_maximum_good_subtree_score
2+
3+
// #Hard #2025_06_08_Time_414_ms_(100.00%)_Space_66.06_MB_(100.00%)
4+
5+
import kotlin.math.abs
6+
import kotlin.math.max
7+
8+
class Solution {
9+
private var ans: Long = 0
10+
fun goodSubtreeSum(vals: IntArray, par: IntArray): Int {
11+
val n = vals.size
12+
val adj: Array<MutableList<Int>> = Array<MutableList<Int>>(n) { mutableListOf() }
13+
for (i in 1..<n) {
14+
adj[par[i]].add(i)
15+
}
16+
this.ans = 0
17+
dfs(0, vals, adj)
18+
return ((this.ans % MOD + MOD) % MOD).toInt()
19+
}
20+
21+
private fun dfs(u: Int, vals: IntArray, adj: Array<MutableList<Int>>): MutableMap<Int, Int> {
22+
// du: The DP map for the subtree at node u.
23+
// Key: bitmask of digits. Value: max sum for that combination of digits.
24+
val du: MutableMap<Int, Int> = HashMap<Int, Int>()
25+
// Base case: A sum of 0 is possible with an empty set of digits (mask 0).
26+
du.put(0, 0)
27+
// Process the current node's value.
28+
val s = abs(vals[u]).toString()
29+
if (hasUniqueDigits(s)) {
30+
var mask = 0
31+
for (c in s.toCharArray()) {
32+
mask = mask or (1 shl (c.code - '0'.code))
33+
}
34+
du.put(mask, vals[u])
35+
}
36+
for (v in adj[u]) {
37+
val dv = dfs(v, vals, adj)
38+
val duSnapshot: MutableMap<Int, Int> = HashMap<Int, Int>(du)
39+
for (entryV in dv.entries) {
40+
val mv: Int = entryV.key
41+
val sv: Int = entryV.value
42+
for (entryU in duSnapshot.entries) {
43+
val mu: Int = entryU.key
44+
val su: Int = entryU.value
45+
// If the digit sets are disjoint (no common bits in masks), we can combine
46+
// them.
47+
if ((mu and mv) == 0) {
48+
val newMask = mu or mv
49+
val newSum = su + sv
50+
// Update `du` with the best possible sum for the new combined mask.
51+
du.put(
52+
newMask,
53+
max(du.getOrDefault(newMask, Int.Companion.MIN_VALUE), newSum),
54+
)
55+
}
56+
}
57+
}
58+
}
59+
// After processing all children, the max value in `du` is the "good" sum for the subtree at
60+
// u.
61+
// Initialize with a very small number to correctly find the maximum, even if sums are
62+
// negative.
63+
var maxSubtreeSum = Int.Companion.MIN_VALUE
64+
for (sum in du.values) {
65+
maxSubtreeSum = max(maxSubtreeSum, sum)
66+
}
67+
// Add this subtree's best sum to the total answer.
68+
// If du is empty (should not happen due to {0:0}), we add 0.
69+
this.ans += (if (maxSubtreeSum == Int.Companion.MIN_VALUE) 0 else maxSubtreeSum).toLong()
70+
return du
71+
}
72+
73+
private fun hasUniqueDigits(s: String): Boolean {
74+
val digits: MutableSet<Char> = HashSet<Char>()
75+
for (c in s.toCharArray()) {
76+
if (!digits.add(c)) {
77+
return false
78+
}
79+
}
80+
return true
81+
}
82+
83+
companion object {
84+
private const val MOD = 1000000007
85+
}
86+
}

0 commit comments

Comments
 (0)