Weekly Quest #1: Sliding Sum Mastery
Habla Computing
Boosting digital transformation through functional programming & language-driven architectures
This article is part of the series Weekly Quest, where each week we present a unique programming challenge designed for Q language. There are two challenge categories, the shortest code and the fastest execution time. The chosen winners will have their solutions featured in the following week's quest.?The tests will be executed using Kdb+ 4.1.
This week′s challenge is called "Sliding sum", inspired by a quaint village game! My uncle Tim, a resident of this village, shared a curious tradition with me. In their forest, players are tasked with selecting n adjacent trees, aiming to maximize the sum of their heights.
Your mission: write a Q function that, given a window size and a list of tree heights, determines the maximum sum achievable by selecting n adjacent trees.
Input
Output
Example
Input:
Output:
Explanation:
Selecting the trees with heights 6, 3, and 8 gives a sum of 17, which is the maximum possible.
Limits:
In the test cases the window size will be always lower or equal than the length of the numbers_list.
All tree heights will be equal or greater than zero.
Write your Q function as a reply to this article. The function should take the window size as the first parameter and the list of heights as the second parameter. Let your Q expertise shine, and may the best solution prevail!
Happy qoding!
Maths+CS Student at St Catherine's College Oxford
8 个月Worth noting that msum can overflow on some smaller int types. {max sum (x-1) prev\ y} is an alternative
All Things Technology at Tradefeedr
8 个月Just to add a slightly different solution: q){ max sum flip neg[x]_x#'{1_x}\[y] }[3;] 2, 4, 1, 5, 6, 3, 8, 2 17 edit, faster version (found an old sliding window function from advent of code): q) {max sum flip neg[x]_flip next\[x-1;y]}[3; 2 4 1 5 6 3 8 2] 17
Lead Architect of PyKX at KX
8 个月Here's my version to just get the maximum sum for the window {max x msum y} Less complex than Alex's who is getting you back the trees!
KDB/Q Consultant | Blogger | DefconQ | Data Intellect
8 个月Just a quick first attempt q) t asc neg[til 3]+first where max[s]= s:3 msum t:2 4 1 5 6 3 8 2 6 3 8