Logo
TGCATALOG
Catálogo Selecciones Blog
Golang  LeetCode

Golang LeetCode

Tareas de LeetCode en Golang. Soluciones con código y explicaciones.

Sin valoraciones
374
01.12.2026
374
01.12.2026
Sin valoraciones
374
01.12.2026
Redirección segura vía bot
О канале

Tareas de LeetCode en Golang. Soluciones con código y explicaciones.

Подписчиков —
Тематика Tecnología
Ссылка @easy_golang_task

También te recomendamos

Kekaton AI  Voz en off y clon de voz
Kekaton AI Voz en off y clon de voz
Bot

bot de IA para clonar texto a voz y voz en Telegram. Cree audio utilizando la red neuronal de forma rápida y fácil.

Descripción

Canal con soluciones para tareas populares de LeetCode en Go. Concéntrate en algoritmos optimizados, uso eficiente de memoria y código idiomático. Ayuda a preparar entrevistas técnicas en empresas que utilizan Golang.

Últimas publicaciones

Golang  LeetCode
Golang LeetCode
🔒Открыть пост
и посмотреть медиа
Задача: 1402. Reducing Dishes Сложность: hard Шеф-повар собрал данные об уровне удовлетворенности от своих n блюд. Шеф может приготовить любое блюдо за 1 единицу времени. Коэффициент удовольствия от блюда определяется как время, затраченное на приготовление этого блюда вместе с предыдущими блюдами, умноженное на уровень удовлетворенности от этого блюда, то есть time[i] * satisfaction[i]. Верните максимальную сумму коэффициентов удовольствия, которую шеф-повар может получить после приготовления некоторого количества блюд. Блюда можно готовить в любом порядке, и шеф может отказаться от некоторых блюд, чтобы достичь максимального значения. Пример: Input: satisfaction = [-1,-8,0,5,-9] Output: 14 Explanation: After Removing the second and last dish, the maximum total like-time coefficient will be equal to (-1*1 + 0*2 + 5*3 = 14). Each dish is prepared in one unit of time. 👨💻 Алгоритм: 1⃣Отсортируйте массив satisfaction в порядке возрастания. 2⃣Создайте таблицу мемоизации memo размером N x N и инициализируйте все значения -1, что будет означать, что ответ для всех состояний еще не рассчитан. 3⃣Реализуйте функцию, которая вызывается с параметрами index = 0 и time = 1, чтобы найти ответ: Если достигнут конец массива, т.е. index == satisfaction.length, верните 0, так как больше нет блюд для приготовления и нельзя получить дополнительное значение. Если значение в массиве memo для пары {index, time} не равно -1, верните это значение, так как это подразумевает, что данная подзадача уже была решена; поэтому рекурсивный вызов не требуется, и можно вернуть сохраненное значение из таблицы memo. Рассчитайте максимум из двух вариантов: - добавьте значение коэффициента для данного блюда satisfaction[index] * time к рекурсивному результату с index = index + 1 и time = time + 1. - пропустите текущее блюдо и сделайте рекурсивный вызов для index = index + 1 и time = time. 😎 Решение: import "sort" func maxSatisfaction(satisfaction []int) int { sort.Ints(satisfaction) memo := make([][]int, len(satisfaction)+1) for i := range memo { memo[i] = make([]int, len(satisfaction)+1) for j := range memo[i] { memo[i][j] = -1 } } var findMaxSatisfaction func(satisfaction []int, memo [][]int, index, time int) int findMaxSatisfaction = func(satisfaction []int, memo [][]int, index, time int) int { if index == len(satisfaction) { return 0 } if memo[index][time] != -1 { return memo[index][time] } memo[index][time] = max(satisfaction[index]*time+findMaxSatisfaction(satisfaction, memo, index+1, time+1), findMaxSatisfaction(satisfaction, memo, index+1, time)) return memo[index][time] } return findMaxSatisfaction(satisfaction, memo, 0, 1) } func max(a, b int) int { if a > b { return a } return b } Ставь 👍 и забирай 📚 Базу знаний
Golang LeetCode

Reseñas de canal Golang LeetCode

Inicia sesión para dejar una reseña

Solo los usuarios registrados pueden compartir su opinión.

Aún no hay reseñas

¡Sé el primero en compartir tu experiencia con este recurso!

Recursos similares

Loading
Cambiar a tema claro
Inicio Catálogo Selecciones Blog Entrar