-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy path2865-beautiful-towers-i.js
More file actions
44 lines (37 loc) · 1.25 KB
/
2865-beautiful-towers-i.js
File metadata and controls
44 lines (37 loc) · 1.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 2865. Beautiful Towers I
* https://leetcode.com/problems/beautiful-towers-i/
* Difficulty: Medium
*
* You are given an array heights of n integers representing the number of bricks in n
* consecutive towers. Your task is to remove some bricks to form a mountain-shaped tower
* arrangement. In this arrangement, the tower heights are non-decreasing, reaching a
* maximum peak value with one or multiple consecutive towers and then non-increasing.
*
* Return the maximum possible sum of heights of a mountain-shaped tower arrangement.
*/
/**
* @param {number[]} heights
* @return {number}
*/
var maximumSumOfHeights = function(heights) {
const n = heights.length;
let result = 0;
for (let peak = 0; peak < n; peak++) {
let currentSum = heights[peak];
let prevHeight = heights[peak];
for (let i = peak - 1; i >= 0; i--) {
const currentHeight = Math.min(heights[i], prevHeight);
currentSum += currentHeight;
prevHeight = currentHeight;
}
prevHeight = heights[peak];
for (let i = peak + 1; i < n; i++) {
const currentHeight = Math.min(heights[i], prevHeight);
currentSum += currentHeight;
prevHeight = currentHeight;
}
result = Math.max(result, currentSum);
}
return result;
};