mirror of
https://github.com/krahets/hello-algo.git
synced 2026-11-10 16:00:36 +08:00
* Retranslate the complete English edition from Simplified Chinese * Polish three English explanations after reader-focused review
35 lines
852 B
JavaScript
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}`);
|