Skip to content

Added tasks 3572-3579 #828

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

Merged
merged 5 commits into from
Jun 10, 2025
Merged
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,45 @@
package g3501_3600.s3572_maximize_ysum_by_picking_a_triplet_of_distinct_xvalues

// #Medium #Array #Hash_Table #Sorting #Greedy #Heap_Priority_Queue
// #2025_06_10_Time_5_ms_(100.00%)_Space_82.11_MB_(56.00%)

class Solution {
fun maxSumDistinctTriplet(x: IntArray, y: IntArray): Int {
var index = -1
var max = -1
var sum = 0
for (i in y.indices) {
if (y[i] > max) {
max = y[i]
index = i
}
}
sum += max
if (max == -1) {
return -1
}
var index2 = -1
max = -1
for (i in y.indices) {
if (y[i] > max && x[i] != x[index]) {
max = y[i]
index2 = i
}
}
sum += max
if (max == -1) {
return -1
}
max = -1
for (i in y.indices) {
if (y[i] > max && x[i] != x[index] && x[i] != x[index2]) {
max = y[i]
}
}
if (max == -1) {
return -1
}
sum += max
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,30 @@
package g3501_3600.s3573_best_time_to_buy_and_sell_stock_v

// #Medium #Array #Dynamic_Programming #2025_06_10_Time_27_ms_(100.00%)_Space_48.69_MB_(80.00%)

import kotlin.math.max

class Solution {
fun maximumProfit(prices: IntArray, k: Int): Long {
val n = prices.size
var prev = LongArray(n)
var curr = LongArray(n)
for (t in 1..k) {
var bestLong = -prices[0].toLong()
var bestShort = prices[0].toLong()
curr[0] = 0
for (i in 1..<n) {
var res = curr[i - 1]
res = max(res, prices[i] + bestLong)
res = max(res, -prices[i] + bestShort)
curr[i] = res
bestLong = max(bestLong, prev[i - 1] - prices[i])
bestShort = max(bestShort, prev[i - 1] + prices[i])
}
val tmp = prev
prev = curr
curr = tmp
}
return prev[n - 1]
}
}
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,67 @@
package g3501_3600.s3574_maximize_subarray_gcd_score

// #Hard #Array #Math #Enumeration #Number_Theory
// #2025_06_10_Time_19_ms_(100.00%)_Space_50.12_MB_(100.00%)

import kotlin.math.max

class Solution {
fun maxGCDScore(nums: IntArray, k: Int): Long {
var mx = 0
for (x in nums) {
mx = max(mx, x)
}
val width = 32 - Integer.numberOfLeadingZeros(mx)
val lowBitPos: Array<MutableList<Int>> = Array<MutableList<Int>>(width) { _ -> ArrayList<Int>() }
val intervals = Array<IntArray>(width + 1) { IntArray(3) }
var size = 0
var ans: Long = 0
for (i in nums.indices) {
val x = nums[i]
val tz = Integer.numberOfTrailingZeros(x)
lowBitPos[tz].add(i)
for (j in 0..<size) {
intervals[j][0] = gcd(intervals[j][0], x)
}
intervals[size][0] = x
intervals[size][1] = i - 1
intervals[size][2] = i
size++
var idx = 1
for (j in 1..<size) {
if (intervals[j][0] != intervals[j - 1][0]) {
intervals[idx][0] = intervals[j][0]
intervals[idx][1] = intervals[j][1]
intervals[idx][2] = intervals[j][2]
idx++
} else {
intervals[idx - 1][2] = intervals[j][2]
}
}
size = idx
for (j in 0..<size) {
val g = intervals[j][0]
val l = intervals[j][1]
val r = intervals[j][2]
ans = max(ans, g.toLong() * (i - l))
val pos = lowBitPos[Integer.numberOfTrailingZeros(g)]
val minL = if (pos.size > k) max(l, pos[pos.size - k - 1]) else l
if (minL < r) {
ans = max(ans, g.toLong() * 2 * (i - minL))
}
}
}
return ans
}

private fun gcd(a: Int, b: Int): Int {
var a = a
var b = b
while (a != 0) {
val tmp = a
a = b % a
b = tmp
}
return b
}
}
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,84 @@
package g3501_3600.s3575_maximum_good_subtree_score

// #Hard #Array #Dynamic_Programming #Depth_First_Search #Tree #Bit_Manipulation #Bitmask
// #2025_06_10_Time_71_ms_(100.00%)_Space_78.07_MB_(0.00%)

import kotlin.math.max

class Solution {
private val digits = 10
private val full = 1 shl digits
private val neg = Long.Companion.MIN_VALUE / 4
private val mod = 1e9.toLong() + 7
private lateinit var tree: Array<ArrayList<Int>>
private lateinit var `val`: IntArray
private lateinit var mask: IntArray
private lateinit var isOk: BooleanArray
private var res: Long = 0

fun goodSubtreeSum(vals: IntArray, par: IntArray): Int {
val n = vals.size
`val` = vals
mask = IntArray(n)
isOk = BooleanArray(n)
for (i in 0..<n) {
var m = 0
var v = vals[i]
var valid = true
while (v > 0) {
val d = v % 10
if (((m shr d) and 1) == 1) {
valid = false
break
}
m = m or (1 shl d)
v /= 10
}
mask[i] = m
isOk[i] = valid
}
tree = Array(n) { initialCapacity: Int -> ArrayList(initialCapacity) }
val root = 0
for (i in 1..<n) {
tree[par[i]].add(i)
}
dfs(root)
return (res % mod).toInt()
}

private fun dfs(u: Int): LongArray {
var dp = LongArray(full)
dp.fill(neg)
dp[0] = 0
if (isOk[u]) {
dp[mask[u]] = `val`[u].toLong()
}
for (v in tree[u]) {
val child = dfs(v)
val newDp = dp.copyOf(full)
for (m1 in 0..<full) {
if (dp[m1] < 0) {
continue
}
val remain = full - 1 - m1
var m2 = remain
while (m2 > 0) {
if (child[m2] < 0) {
m2 = (m2 - 1) and remain
continue
}
val newM = m1 or m2
newDp[newM] = max(newDp[newM], dp[m1] + child[m2])
m2 = (m2 - 1) and remain
}
}
dp = newDp
}
var best: Long = 0
for (v in dp) {
best = max(best, v)
}
res = (res + best) % mod
return dp
}
}
Loading