본문 바로가기
코딩테스트(알고리즘)/leetCode

[leetCode] 11. Container With Most Water (Javascript)

by Cafe Mocha 2022. 6. 25.

(5) Container With Most Water - LeetCode

 

Container With Most Water - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


접근 : 투포인터

 

부르트포스로 풀면 시간초과 발생

투포인터를 활용해 문제풀이

 

Javascript

let input = require("fs")
  .readFileSync("input.txt") //"/dev/stdin"
  .toString()
  .split("\n")
  .map((val) => val.trim());

function solution(input) {
  //input
  let height = input[0].split(" ").map((v) => +v);
  //Submit
  let left = 0;
  let right = height.length - 1;

  let max = -Infinity;

  while (left < right) {
    let width = right - left;
    let vertical = Math.min(height[left], height[right]);
    let water = width * vertical;

    max = Math.max(max, water);

    if (height[left] > height[right]) right--;
    else left++;
  }

  console.log(max);
}

solution(input);