Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice.
deffuncion1(lista: list[int],target:int) -> list[int]:""" Esta funcion es O(N^2) en tiempo, y O(1) en espacio. """for i, vali inenumerate(lista):for j, valj inenumerate(lista[i:]):if valj + vali == target:return [i, j]deffuncion2(lista: list[int],target:int) -> list[int]:""" Esta funcion es O(N) en tiempo y O(N) en espacio. """ diccionario ={}for i, valor inenumerate(lista): valor2 = target - valorif valor2 in diccionario:return [i, diccionario[valor2]]else: diccionario[valor]= i
Best time to buy and sell stock
Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit. Note that you cannot sell a stock before you buy one.
Example:
nums = [7,1,5,3,6,4]output =5Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 -1 = 5. Not 7 - 1 = 6, as selling price needs to be larger than buying price.
Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(N) time and without using the division operation.
Example:
nums = [1,2,3,4]output = [24,12,8,6]
Solucion
deffuncion(lista: list[int]) ->bool:""" O(N^2), suponiendo que no tenemos las restricciones que nos imponen """ producto =1for i, vali inenumerate(lista): producto *= vali res = []for i, vali inenumerate(lista): res.append(int(producto / vali))return resdeffuncion2(lista: list[int]) ->bool:""" O(N^2), sin utilizar la division """ res = []for i, vali inenumerate(lista):if i ==0: izq = []else: izq = lista[:i]elif i ==len(lista)-1: der = []else: der = lista[i +1:] new_lista = izq + der producto =1for i, val inenumerate(new_lista): producto *= val res.append(producto)return resdeffuncion3(lista: list[int]) ->bool:""" O(N) """ n =len(lista)# Inicializar las listas de productos a la izquierda y a la derecha# Inicialmente todos los valores son 1, se crean tantos elementos# como elementos tenga la lista original izq = [1] * n der = [1] * n# Calcular el producto acumulativo a la izquierda de cada índicefor i inrange(1, n): izq[i]= izq[i -1]* lista[i -1]# Calcular el producto acumulativo a la derecha de cada índicefor i inreversed(range(n -1)): der[i]= der[i +1]* lista[i +1]# Calcular el producto de los elementos excepto el mismofor i inrange(n): lista[i]= izq[i]* der[i]return lista