Skip to content

Commit 0c30db1

Browse files
authored
Create 2234-maximum-total-beauty-of-the-gardens.js
1 parent f6c894f commit 0c30db1

File tree

1 file changed

+93
-0
lines changed

1 file changed

+93
-0
lines changed
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
/**
2+
* @param {number[]} flowers
3+
* @param {number} newFlowers
4+
* @param {number} target
5+
* @param {number} full
6+
* @param {number} partial
7+
* @return {number}
8+
*/
9+
const maximumBeauty = function (flowers, newFlowers, target, full, partial) {
10+
flowers.sort((x, y) => x - y)
11+
flowers = flowers.map((x) => Math.min(x, target))
12+
let a = flowers,
13+
n = a.length,
14+
k = newFlowers,
15+
pre = preSum(a),
16+
bi = new Bisect()
17+
let res = 0
18+
for (let i = 0; i <= n; i++) {
19+
if (i < n && a[n - 1 - i] == target) continue
20+
let step = i * target - (pre[n] - pre[n - i])
21+
if (step <= k) {
22+
let beauty
23+
if (i == n) {
24+
beauty = i * full
25+
} else {
26+
let minPartial = BinarySearch(a[0], target, step, i)
27+
beauty = i * full + minPartial * partial
28+
}
29+
if (beauty > res) res = beauty
30+
}
31+
}
32+
return res
33+
34+
function BinarySearch (low, high, step, i) {
35+
while (low < high - 1) {
36+
let mid = low + parseInt((high - low) / 2)
37+
if (possible(mid, step, i)) {
38+
low = mid
39+
} else {
40+
high = mid
41+
}
42+
}
43+
return low
44+
}
45+
46+
function possible (m, step, i) {
47+
let idx = bi.bisect_left(a, m, 0, n - i)
48+
let need = m * idx - pre[idx]
49+
return need <= k - step
50+
}
51+
}
52+
53+
/////////////////// Template /////////////////////////////////
54+
function Bisect() {
55+
return { insort_right, insort_left, bisect_left, bisect_right }
56+
function insort_right(a, x, lo = 0, hi = null) {
57+
lo = bisect_right(a, x, lo, hi)
58+
a.splice(lo, 0, x)
59+
}
60+
function bisect_right(a, x, lo = 0, hi = null) {
61+
// > upper_bound
62+
if (lo < 0) throw new Error('lo must be non-negative')
63+
if (hi == null) hi = a.length
64+
while (lo < hi) {
65+
let mid = parseInt((lo + hi) / 2)
66+
a[mid] > x ? (hi = mid) : (lo = mid + 1)
67+
}
68+
return lo
69+
}
70+
function insort_left(a, x, lo = 0, hi = null) {
71+
lo = bisect_left(a, x, lo, hi)
72+
a.splice(lo, 0, x)
73+
}
74+
function bisect_left(a, x, lo = 0, hi = null) {
75+
// >= lower_bound
76+
if (lo < 0) throw new Error('lo must be non-negative')
77+
if (hi == null) hi = a.length
78+
while (lo < hi) {
79+
let mid = parseInt((lo + hi) / 2)
80+
a[mid] < x ? (lo = mid + 1) : (hi = mid)
81+
}
82+
return lo
83+
}
84+
}
85+
86+
const preSum = (a) => {
87+
let pre = [0]
88+
for (let i = 0; i < a.length; i++) {
89+
pre.push(pre[i] + a[i])
90+
}
91+
return pre
92+
}
93+
//////////////////////////////////////////////////////////////////

0 commit comments

Comments
 (0)