[HAI] week3 max area
https://leetcode.com/problems/container-with-most-water/description/?source=submission-acmain
parent
a54b5b8996
commit
656b5c6eb5
@ -0,0 +1,3 @@
|
|||||||
|
import { maxArea } from "./maxArea";
|
||||||
|
|
||||||
|
export default maxArea;
|
||||||
@ -0,0 +1,13 @@
|
|||||||
|
import { describe, it, expect } from "vitest";
|
||||||
|
import { maxArea } from "./maxArea.ts";
|
||||||
|
|
||||||
|
describe("maxArea", () => {
|
||||||
|
|
||||||
|
it("[1,8,6,2,5,4,8,3,7] => 49", () => {
|
||||||
|
expect(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])).toBe(49);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("[1,1] => 1", () => {
|
||||||
|
expect(maxArea([1, 1])).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
export function maxArea(height: number[]): number {
|
||||||
|
let L = 0;
|
||||||
|
let R = height.length - 1;
|
||||||
|
let res = 0;
|
||||||
|
|
||||||
|
while (L <= R) {
|
||||||
|
let hL = height[L];
|
||||||
|
let hR = height[R];
|
||||||
|
let currArea = Math.min(hL, hR) * (R - L);
|
||||||
|
if (currArea > res) res = currArea;
|
||||||
|
hR > hL ? L++ : R--;
|
||||||
|
}
|
||||||
|
|
||||||
|
return res;
|
||||||
|
};
|
||||||
Loading…
Reference in New Issue