Files
hello-algo/en/codes/javascript/chapter_greedy/max_capacity.js
Yudong Jin 14c314c08c Retranslate the complete English edition from Simplified Chinese (#2010)
* Retranslate the complete English edition from Simplified Chinese

* Polish three English explanations after reader-focused review
2026-10-31 03:35:51 +08:00

35 lines
852 B
JavaScript

/**
* File: max_capacity.js
* Created Time: 2023-09-02
* Author: Justin (xiefahit@gmail.com)
*/
/* Maximum container capacity: greedy algorithm */
function maxCapacity(ht) {
// Initialize i and j at opposite ends of the array
let i = 0,
j = ht.length - 1;
// The initial maximum capacity is 0
let res = 0;
// Repeatedly make greedy choices until the two sides meet
while (i < j) {
// Update the maximum capacity
const cap = Math.min(ht[i], ht[j]) * (j - i);
res = Math.max(res, cap);
// Move the shorter side inward
if (ht[i] < ht[j]) {
i += 1;
} else {
j -= 1;
}
}
return res;
}
/* Driver code */
const ht = [3, 8, 5, 2, 7, 7, 3, 4];
// Greedy algorithm
const res = maxCapacity(ht);
console.log(`Maximum capacity: ${res}`);