Introducción

1

Arrays y Strings para resolver algoritmos avanzados

2

Arrays y Strings en detalle

Dos Apuntadores

3

Patrón de Dos Apuntadores

4

Verifying Alien Dictionary: análisis del problema

5

Solución de Verifying Alien Dictionary

6

Playground: Verifying Alien Dictionary

7

Programando Verifying Alien Dictionary con JavaScript

8

Merge Two Sorted Lists: análisis del problema

9

Solución de Merge Two Sorted Lists

10

Playground: Merge Two Sorted Lists

11

Programando Merge Two Sorted Lists con Python

12

Container With Most Water: análisis del problema

13

Solución de Container With Most Water

14

Playground: Container with Most Water

15

Programando Container With Most Water con Java

16

Reto: Trapping Rain Water

17

Ejercicios recomendados de Dos Apuntadores

18

Ejercicios resueltos de Dos Apuntadores

Ventana Deslizante

19

Patrón de Ventana Deslizante

20

Longest Substring Without Repeating Characters: análisis del problema

21

Solución de Longest Substring Without Repeating Characters

22

Playground: Longest Substring Without Repeating Characters

23

Programando Longest Substring Without Repeating Characters con Python

24

Ejercicios recomendados de Ventana Deslizante

25

Ejercicios resueltos de Ventana Deslizante

Búsqueda Binaria

26

Algoritmo de Búsqueda Binaria

27

Search in Rotated Arrays: análisis del problema

28

Solución de Search in Rotated Arrays

29

Playground: Search in Rotated Arrays

30

Programando Search in Rotated Arrays

31

Search 2D Array Matrix: análisis del problema

32

Solución de Search 2D Array Matrix

33

Playground: Search 2D Array Matrix

34

Programando Search 2D Array Matrix

Próximos pasos

35

Toma el Curso Avanzado de Algoritmos: Estructuras de Datos Lineales

No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Convierte tus certificados en títulos universitarios en USA

Antes: $249

Currency
$209

Paga en 4 cuotas sin intereses

Paga en 4 cuotas sin intereses
Suscríbete

Termina en:

19 Días
4 Hrs
15 Min
2 Seg

Playground: Container with Most Water

14/35

Aportes 30

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

export function maxArea(alturas) {
  let pointer1 = 0;
  let pointer2 = alturas.length-1
  let maxArea = 0
  while (pointer1 < pointer2) {

    let minHeight = Math.min(alturas[pointer1], alturas[pointer2])

    let currentArea = (pointer2-pointer1) * minHeight
    if (currentArea > maxArea) {
      maxArea = currentArea
    }
    if (alturas[pointer1] <  alturas[pointer2]) {
      pointer1 ++
    } else {
      pointer2 --
    }
  }
  return maxArea
}
```js export function maxArea(alturas) { // Tu código aquí 👈..... let p1 = 0 let p2 = alturas.length - 1 let maxWaterArea = 0 while (p1 <= p2) { let minHeight = Math.min(alturas[p1], alturas[p2]); let waterBase = (p2 - p1); let currentArea = minHeight * waterBase; if (currentArea > maxWaterArea) { maxWaterArea = currentArea; } if (alturas[p1] > alturas[p2]) { p2--; } else { p1++; } } return maxWaterArea; } ```export function maxArea(alturas) { // Tu código aquí 👈..... let p1 = 0 let p2 = alturas.length - 1 let maxWaterArea = 0 while (p1 <= p2) { let minHeight = Math.min(alturas\[p1], alturas\[p2]); let waterBase = (p2 - p1); let currentArea = minHeight \* waterBase; if (currentArea > maxWaterArea) { maxWaterArea = currentArea; } if (alturas\[p1] > alturas\[p2]) { p2--; } else { p1++; } } return maxWaterArea; }
Con python: ```python def container_with_most_water(heights): # Pointers initialization p1 = 0 p2 = len(heights) - 1 # Variables base = p2 - p1 max_value = 0 # Calculate until base is grater than zero while base > 0: base = p2 - p1 if base == 0: # Stop break # Area must be calculated with the shorter height min_height = min(heights[p1], heights[p2]) current_value = base * min_height # Save max area, heights and positions if current_value > max_value: max_value = current_value # Update pointers, move pointer for shorter height if heights[p1] <= heights[p2]: p1 += 1 elif heights[p1] > heights[p2]: p2 -= 1 return max_value h = [1, 8, 6, 2, 5, 4, 8, 3, 7] maximum = container_with_most_water(h) print(maximum) h1 = [8, 1, 6, 2, 5, 4, 1, 3, 7] maximum = container_with_most_water(h1) print(maximum) ```Con javascript: ````js function maxArea(alturas) { // Tu código aquí 👈 // Pointers initialization let p1 = 0; let p2 = alturas.length - 1; // Variables let base = p2 - p1; let max_value = 0; // Calculate until base is grater than zero while (base > 0) { base = p2 - p1; if (base == 0) { break; } // Stop, no more areas // Area must be calculated with the shorter height let min_height = Math.min(alturas[p1], alturas[p2]); let current_value = base * min_height; // Save max area, heights and positions if (current_value > max_value) { max_value = current_value; } // Update pointers, move pointer for shorter height if (alturas[p1] <= alturas[p2]) { p1 += 1; } else if (alturas[p1] > alturas[p2]) { p2 -= 1; } } return max_value; } ```function maxArea(alturas) { *// Tu código aquí 👈* *// Pointers initialization* let p1 = 0; let p2 = alturas.length - 1; *// Variables* let base = p2 - p1; let max\_value = 0; *// Calculate until base is grater than zero* while (base > 0) { base = p2 - p1; if (base == 0) { break; } *// Stop, no more areas* *// Area must be calculated with the shorter height* let min\_height = Math.min(alturas\[p1], alturas\[p2]); let current\_value = base \* min\_height; *// Save max area, heights and positions* if (current\_value > max\_value) { max\_value = current\_value; } *// Update pointers, move pointer for shorter height* if (alturas\[p1] <= alturas\[p2]) { p1 += 1; } else if (alturas\[p1] > alturas\[p2]) { p2 -= 1; } } return max\_value;} ````
Solucion con Javascript export function maxArea(alturas) {public class Solution { public int MaxArea(int\[] height) { int left = 0; int rigth = height.Length - 1; int maxArea = 0; while(left < rigth){ maxArea = Math.Max(maxArea, Math.Min(height\[left], height\[rigth]) \* (rigth-left)); if(height\[left] > height\[rigth]) { rigth--; } else { left++; } } return maxArea; }} let pointer1 = 0; let pointer2 = alturas.length - 1; let maxArea = 0; while (pointer1 < pointer2) { maxArea = Math.max(maxArea, Math.min(alturas\[pointer1], alturas\[pointer2]) \* (pointer2 - pointer1)); if (alturas\[pointer1] > alturas\[pointer2]) { pointer2--; } else { pointer1++; } } return maxArea; } ```js export function maxArea(alturas) { let pointer1 = 0; let pointer2 = alturas.length - 1; let maxArea = 0; while (pointer1 < pointer2) { maxArea = Math.max(maxArea, Math.min(alturas[pointer1], alturas[pointer2]) * (pointer2 - pointer1)); if (alturas[pointer1] > alturas[pointer2]) { pointer2--; } else { pointer1++; } } return maxArea; } ```Solucion con C# ```js public class Solution { public int MaxArea(int[] height) { int left = 0; int rigth = height.Length - 1; int maxArea = 0; while(left < rigth){ maxArea = Math.Max(maxArea, Math.Min(height[left], height[rigth]) * (rigth-left)); if(height[left] > height[rigth]) { rigth--; } else { left++; } } return maxArea; } } ```
![](https://static.platzi.com/media/user_upload/with_most_water-e7de08a1-247b-4c36-9fe2-baca3d541aa2.jpg) ```js ```
With Java: ![](https://static.platzi.com/media/user_upload/image-30623819-44a3-439d-8ef3-01b9036bc893.jpg)
CODIGO EN JAVA: ```js import java.util.ArrayList; public class Main { public static void main(String[] args) { System.out.println("Hello world!"); int [] height = {8,1,6,2,5,4,1,3,7}; int position1 = 0; int largo1= height[position1]; int position2 = height.length-1; int largo2 = height[position2]; int result = area( height,largo1,largo2,position1,position2); System.out.println("El área en su maxima expresión es: " + result); } private static int area(int [] height, int largo1, int largo2, int position1, int position2) { ArrayList<Integer> resultados = new ArrayList<>(); int aea = 0; while (position2 > 1){ int base = position2 - position1; if( largo1 < largo2){ aea = largo1 * base; resultados.add(aea); System.out.println("area1: " + aea); position1++; largo1 = height[position1]; } else { aea = largo2 * base; resultados.add(aea); System.out.println("area2: " + aea); position2--; largo2 = height[position2]; } } for (int resulta : resultados) { System.out.println("Área total iteradas: " + resulta); } int posibleMayor = resultados.get(0); for (int i = 0; i < resultados.size(); i++) if ( posibleMayor < resultados.get(i)) { posibleMayor = resultados.get(i); System.out.println("El área mayor: " + posibleMayor); } System.out.println("*Este es: " + posibleMayor); return posibleMayor; } } ```import java.util.ArrayList; public class Main { public static void main(String\[] args) { System.out.println("Hello world!"); int \[] height = {8,1,6,2,5,4,1,3,7}; int position1 = 0; int largo1= height\[position1]; int position2 = height.length-1; int largo2 = height\[position2]; int result = area( height,largo1,largo2,position1,position2); System.out.println("El área en su maxima expresión es: " + result); } private static int area(int \[] height, int largo1, int largo2, int position1, int position2) { ArrayList\<Integer> resultados = new ArrayList<>(); int aea = 0; while (position2 > 1){ int base = position2 - position1; if( largo1 < largo2){ aea = largo1 \* base; resultados.add(aea); System.out.println("area1: " + aea); position1++; largo1 = height\[position1]; } else { aea = largo2 \* base; resultados.add(aea); System.out.println("area2: " + aea); position2--; largo2 = height\[position2]; } } for (int resulta : resultados) { System.out.println("Área total iteradas: " + resulta); } int posibleMayor = resultados.get(0); for (int i = 0; i < resultados.size(); i++) if ( posibleMayor < resultados.get(i)) { posibleMayor = resultados.get(i); System.out.println("El área mayor: " + posibleMayor); } System.out.println("\*Este es: " + posibleMayor); return posibleMayor; } }
Codigo en Python ```python def MaxArea(alturas): apuntadorInicio = 0 apuntadorFinal = len(alturas) - 1 max_area = 0 while apuntadorInicio < apuntadorFinal: alto = min(alturas[apuntadorInicio], alturas[apuntadorFinal]) width = apuntadorFinal - apuntadorInicio max_area = max(max_area, alto * width) if alturas[apuntadorInicio] <= alturas[apuntadorFinal]: apuntadorInicio += 1 else: apuntadorFinal -= 1 return max_area ```
Mi codigo en JAVA. ![](https://static.platzi.com/media/user_upload/image-9eed0940-1a37-498e-ab7a-5d08df31cd2a.jpg) ![](https://static.platzi.com/media/user_upload/image-33e04c90-d68c-49cc-89be-3c7405efc153.jpg)
```python def water_containter(array): areas = [] left, right = 0, len(array)-1 while left < right: height = min(array[left], array[right]) width = right - left area = height * width areas.append(area) if array[left] > array[right]: right -= 1 else: left += 1 return max(areas) ```
Implementacion en C++ (no se js) ```js #include <bits/stdc++.h> using namespace std; int main() { vector <int> v; cout << "Elementos del vector: " << endl; int n ; cin >> n; cout << "Llenando el vector" << endl; // [1,8,6,2,5,4,8,3,7] for (int i= 0; i < n; i ++) { int num; cin >> num; v.push_back(num); } int * p1 = &v[0]; int * p2 = &v[n-1]; int maximo = 0; while (p1 < p2) { int base = (p2 - p1); int area = min(*p1,* p2) * base; if (area > maximo) maximo = area; if (*p1 > *p2) { p2--; } else { p1++; } } cout << "El resultado es: " << maximo << endl; return 0; } ```
```js export function maxArea(alturas) { // Tu código aquí 👈 let p1 = 0 let p2 = alturas.length - 1 let area = 0 while (p1 < p2) { let tmp_area = Math.min(alturas[p1], alturas[p2]) * (p2 - p1) area = Math.max(area, tmp_area) if (alturas[p1] > alturas[p2]) { p2-- } else { p1++ } } return area } ```export function maxArea(alturas) {  // Tu código aquí 👈  let p1 = 0  let p2 = alturas.length - 1  let area = 0   while (p1 < p2) {    let tmp\_area = Math.min(alturas\[p1], alturas\[p2]) \* (p2 - p1)    area = Math.max(area, tmp\_area)    if (alturas\[p1] > alturas\[p2]) {      p2--    }    else {      p1++    }  }   return area}
def containerWithMostWater(listaAlt):    areaMax=0    aux=0    p1=0    p2=len(listaAlt)-1        while p1<=p2 and p2>=0:        if listaAlt\[p1]<=listaAlt\[p2]:            aux=listaAlt\[p1]\*(p2-p1)            if aux>areaMax:                areaMax=aux            p1+=1        else:            aux= listaAlt\[p2]\*(p2-p1)            if aux>areaMax:                areaMax=aux            p2-=1    return areaMax
Ésta es mi solución en Python: ```python def max_area(alturas: list) -> int: biggest_area = 0 middle = len(alturas) // 2 i = 0 j = len(alturas) - 1 for _ in range(len(alturas)): n1 = alturas[i] n2 = alturas[j] area = min(n1, n2) * (j - i) if area > biggest_area: biggest_area = area if n1 < n2: i += 1 else: j -= 1 if _ == middle: break return biggest_area ```Y ésta en JS: ```js export function maxArea(alturas) { let biggestArea = 0; const middle = Math.floor(alturas.length / 2); let i = 0; let j = alturas.length - 1; for (let _ = 0; _ < alturas.length; _++) { const n1 = alturas[i]; const n2 = alturas[j]; const area = Math.min(n1, n2) * (j - i); if (area > biggestArea) { biggestArea = area; } if (n1 < n2) { i += 1; } else { j -= 1; } if (_ === middle) { break; } } return biggestArea; } ```
def max\_area(alturas:\[]): area\_max = 0    pointer = 0    pointer\_end = len(alturas) - 1 while pointer < pointer\_end: area = min(alturas\[pointer], alturas\[pointer\_end]) \* (pointer\_end - pointer)         if area > area\_max:            area\_max = area        if alturas\[pointer] >= alturas\[pointer\_end]: pointer\_end -= 1        else:            pointer += 1     return area\_max 
mi solucion antes de ver como lo hacia la profe :3 function containerWithMostWater(elements) { let indexFirstElementSearch = null; let indexLastElementSearch = null; let pointer1 = 0, pointer2 = 1; let result = 0; let isEndSearch = false; for (let i = 1; i < elements.length; i++) { if (pointer2 === elements.length || pointer1 === elements.length) { pointer2 = elements.length - 1; pointer1 = pointer2; isEndSearch = true; } const indexFound = returnIndexWithMostValue(elements, pointer1, pointer2); if (isDefaultValueIndexFound(indexFirstElementSearch)) { indexFirstElementSearch = indexFound.toString(); } else if (isDefaultValueIndexFound(indexLastElementSearch)) { indexLastElementSearch = indexFound.toString(); } if (indexFirstElementSearch === null || indexLastElementSearch === null) { pointer1 = pointer2 + 1; pointer2 = pointer1 + 1; continue; } const area = (parseInt(indexLastElementSearch) - parseInt(indexFirstElementSearch)) \* Math.min(elements\[parseInt(indexFirstElementSearch)], elements\[parseInt(indexLastElementSearch)]); if (area > result) { result = area; } if ( returnIndexWithMostValue(elements, parseInt(indexFirstElementSearch), parseInt(indexLastElementSearch)) === parseInt(indexLastElementSearch) ) { indexFirstElementSearch = null; } else { indexLastElementSearch = null; } pointer1 = pointer2 + 1; pointer2 = pointer1 + 1; if (isEndSearch) { break; } } return result; } function isDefaultValueIndexFound(element) { return element === null; } function returnIndexWithMostValue(elements, index1, index2) { if (elements\[index1] > elements\[index2] || elements\[index1] === elements\[index2]) { return index1; } return index2; }
```java public static void main(String[] args) { int[] heights = {1, 8, 6, 2, 5, 4, 8, 3, 7}; System.out.println(containerWithMostWater(heights)); } public static int containerWithMostWater(int[] heights) { int p1 = 0; int p2 = heights.length - 1; int areaMax = 0; while (p1 < p2) { int area = (Math.min(heights[p1], heights[p2])) * (p2 - p1); if (area > areaMax) { areaMax = area; } if (heights[p1] >= heights[p2]) { p2--; } else { p1++; } } return areaMax; } } ```

Mi solucion en python, javascript es muy duro 🤕

def container_with_most_water(list=[1, 8, 6, 2, 5, 4, 8, 3, 7]):
  max_area = 0
  p1=0
  p2=len(list)-1
  while p2 > p1:
    area = min(list[p1], list[p2]) * (p2-p1)
    if area > max_area:
      max_area = area
    if list[p1] < list[p2]:
      p1 += 1
    else:
      p2 -= 1
  return max_area

Podemos uzar el siguiente enfoque:

function maxArea(height) {
    let maxWater = 0;
    let left = 0;
    let right = height.length - 1;

    while (left < right) {
        const hLeft = height[left];
        const hRight = height[right];
        const width = right - left;
        const minHeight = Math.min(hLeft, hRight);
        const area = width * minHeight;

        maxWater = Math.max(maxWater, area);

        if (hLeft < hRight) {
            left++;
        } else {
            right--;
        }
    }

    return maxWater;
}

export function maxArea(alturas) {
  // Tu código aquí 👈
  var p1 = 0, p2 = alturas.length - 1, maxArea = 0;
  while (p1 != p2) {
    maxArea = Math.max(maxArea, (p2 - p1) * Math.min(alturas[p1], alturas[p2]));
    if (alturas[p1] - alturas[p2] < 0) {
      p1 += 1;
    } else {
      p2 -= 1;
    }
  }
  return maxArea;
}

le pedi a la IA que me convirtiera mi codigo python a Js solo para er la serpentina 🎉 🐧🐍

.
.
.
.

Para probar el código en node js:

function maxArea(alturas) {
// Tu código aquí 👈
const heigth = alturas;
let maxArea = 0;
let p1 = 0;
let p2 = heigth.length - 1;
console.log(maxArea, p1, p2);

while (p1 < p2) {
    let minHeight = Math.min(heigth[p1], heigth[p2]);
    let area = (p2 - p1) * minHeight;

    if (area > maxArea) {
        maxArea = area;
    }
    if (alturas[p1] <= alturas[p2]) {
        p1++;
    } else {
        p2--;
    }

}

return maxArea;

}

Container With Most Water

I learned a lot with this challenge 💚

def max_area(height):
    """
    T = O(n)
    We only iterate once our list to calculate the area,
    that means that is linear.

    S = O(1)
    We only store 3 variables that regardless of the input
    they do not change their value so it´s linear.
    """
    max_area = 0
    left_pointer, right_pointer = 0, len(height) - 1

    while left_pointer < right_pointer:  # T = O(n)
        area = (right_pointer - left_pointer) * min(height[right_pointer], height[left_pointer])
        max_area = max(max_area, area)
        if height[right_pointer] >= height[left_pointer]:
            left_pointer += 1
        else:
            right_pointer -= 1

    return max_area


if __name__ == '__main__':
    input1 = [1, 8, 6, 2, 5, 4, 8, 3, 7]
    output1 = 49

    input2 = [8, 1, 6, 2, 5, 4, 1, 3, 7]
    output2 = 56

    print(max_area(input1))
    print(max_area((input2)))

Sugiero que se agreguen más casos de prueba, habia hecho un algoritmo que estaba mal, pero pasaban los tests 😕 jaja

Bueno, igual aqui quedo, o(n)

export const maxArea = (heights) => {
  let right = heights.length - 1;
  let left = 0;
  let max = 0;
  for (let i = 0; i < heights.length; i++) {
    const distance = right - left;
    const leftHeight = heights[left];
    const rightHeight = heights[right];
    const maxHeight = Math.min(leftHeight, rightHeight);

    const area = distance * maxHeight;
    if (area > max) max = area
    if (leftHeight > rightHeight) right--
    else left++
  }
  return max;
}

Yo había resuelto este problema hace tiempo, había tratado de hacer lo mismo con dos indices por la izquierda y por la derecha, pero realmente no conocía el patrón two points, y no sabia como aplicarlo de forma más limpia y elegante como con el while p1!=p2, les muestro esta solución en python:

def maxArea(height):
        n = len(height)
        left = 0
        right = n-1
        base = n-1
        max_value = 0

        while base > 0:
            if height[left] <= height[right]:
               max_v = base*height[left]
               if max_value < max_v:
                   max_value = max_v
               left += 1
                

            elif height[left] > height[right]:
                max_v = base*height[right]
                if max_value < max_v:
                    max_value = max_v
                right -= 1

            base -= 1

        return max_value
function containerMostWater(alturas) {
  let p1 = 0;
  let p2 = alturas.length - 1;
  let area = 0;

  while (p1 !== p2) {
    const h = Math.min(alturas[p1], alturas[p2]);
    const b = p2 - p1;
    area = Math.max(area, b * h);

    if (alturas[p1] < alturas[p2]) {
      p1++;
    } else {
      p2--;
    }
  }
  return area;
}
export function maxArea(alturas) {
      let i = 0;
    let j = list.length - 1;
    let max = 0
    while (i !== j) {
        let temp = 0
        if (list[i] < list[j]) {
            temp = list[i] * (j - i);
            i++;
        } else {
            temp = list[j] * (j - i);
            j--
        }

        if (temp > max) {
            max = temp;
        }
    }
    return max;

}

Comparto mi intento :]

function maxArea(heights) {
	let p1 = 0, p2 = heights.length - 1;
	let bestArea = 0;

	while (true) {
		const val1 = heights[p1], val2 = heights[p2]; // Alturas de cada apuntador
		const b = p2 - p1;
		const h = Math.min(val1, val2);
		const area = b * h;

		if (area > bestArea)
			bestArea = area; // Guardar mejor area

		if (val1 > val2) // Recorrer apuntadores
			p2--;
		else
			p1++;

		if (p1 === p2)
			break;
	}

	return bestArea;
}

Comparto mi solucion

export function maxArea(alturas) {
  // Tu código aquí 👈
  let pointer1 = 0;
  let pointer2 = alturas.length - 1;
  let better_area = 0;

  while (pointer1 != pointer2) {
    let small = Math.min(alturas[pointer1], alturas[pointer2]);
    let base = pointer2 - pointer1;

    if ((small * base) > better_area) {
      better_area = (small * base)
    }

    if (alturas[pointer1] == small) {
      pointer1 += 1;
    }
    else {
      pointer2 -= 1;
    }
  }
  return better_area;
}

dejando codigo :

haber si les sirve!

export function maxArea(alturas) {
  // Tu código aquí 👈
  let p1 = alturas.length - 1;
  let area = [];
  let final = 0;
  let p2 = 0;
  let i = 0;

  while (1 < p1 && p2 < p1) {
    if (alturas[p1] < alturas[p2]) {
      area[i] = alturas[p1] * (p1 - p2);
      p1--;
    } else {
      area[i] = alturas[p2] * (p1 - p2);
      p2++;
    }
    i++;
  }

  while (0 <= i) {
    if (final < area[i]) {
      final = area[i];
    }
    i--;
  }
  return final;
}

undefined