?Mastering Algorithms: Sliding Window Pattern ?
Code Example @ https://dartpad.dartlang.org/1e9810331f8d04d2909c5c2c6f7b7ac6
* ???? Sliding Window Pattern ????
*
* - Easy to implement
* - Can be tricky to reason about
* - Good at making O(n^2) Subset / Subarray problems O(n)
Also known as Sliding Window Technique.
Problem Description:
* Write a function called maxConsecutiveSubsetSum that accepts
* a list of integers and an integer n. Return an integer representing
* maximum sum of n consecutive elements in the array.
* n will never be smaller than the length of the list
Details:
This solution implementing the Sliding Window Pattern uses two pointers to frame the edge of the window. The leading pointer (the one with the higher index) is included in our subset / subarray sum, whereas the trailing pointer (the one with the lower index) is excluded.
We begin with the sum of the first n values. We then iterate along the array until our leading pointer is greater than the length of the array. Each step of the way, we calculate the current sum by subtracting the value located at our trailing pointer and adding the value at our leading pointer.
The use of pointers in the solution is not necessary, though it does make the code easier to read. Alternatively, we could use a for loop to iterate over the array. In this case, we would still calculate the sum of the first n elements. Then, we would begin our loop at the n index. We would add n to our current sum and subtract the value at array[index - n]. Essentially, we are doing the same thing, except in this version the index value represents our leading pointer (p2 in the video) and we calculate the value of our trailing pointer (p1 in the video).
Good luck & happy coding!
This implementation uses the Dart programming language, which should be easy to follow if you have experience in JavaScript or Java. A similar implementation in JavaScript is coming soon!
Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «?Mastering Algorithms: Sliding Window Pattern ?», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.
Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.
Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!
Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.