Skip to content

Commit 9497bf0

Browse files
authored
Update 1802-maximum-value-at-a-given-index-in-a-bounded-array.js
1 parent 41402a3 commit 9497bf0

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

1802-maximum-value-at-a-given-index-in-a-bounded-array.js

+30
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,33 @@
1+
/**
2+
* @param {number} n
3+
* @param {number} index
4+
* @param {number} maxSum
5+
* @return {number}
6+
*/
7+
const maxValue = function(n, index, maxSum) {
8+
const { floor, sqrt } = Math
9+
maxSum -= n
10+
if(index < Math.floor(n / 2)) index = n - 1 - index
11+
let left = index // number of element to the left of the index
12+
let right = n - 1 - index // number of element to the right of the index
13+
// the triangle area for the left side if not hitting the boundary
14+
let leftSum = floor((left * (left + 1)) / 2)
15+
// the triangle area for the right side if not hitting the boundary
16+
let rightSum = floor((right * (right + 1)) / 2)
17+
// case: perfect pyramid
18+
if (maxSum <= (rightSum * 2 + right + 1)) return floor(sqrt(maxSum) + 1)
19+
// case: right side hits the boundary
20+
if (maxSum <= (leftSum + rightSum + (left - right) * right + left + 1)) {
21+
const b = 3 + 2 * right
22+
return floor((-b + sqrt(b * b - 8 * (rightSum + 1 - right * right - maxSum))) / 2) + 1 + 1
23+
}
24+
// case: both sides hit boundaries
25+
maxSum -= (leftSum + rightSum + (left - right) * right + left + 1)
26+
return left + 1 + 1 + floor(maxSum / n)
27+
};
28+
29+
// another
30+
131
/**
232
* @param {number} n
333
* @param {number} index

0 commit comments

Comments
 (0)