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

Aprende Ingl茅s, Programaci贸n, AI, Ciberseguridad y m谩s a precio especial.

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

2 D铆as
0 Hrs
10 Min
24 Seg

Playground: Container with Most Water

14/35

Aportes 25

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
}
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