Weekly Quest #1: Sliding Sum Mastery

Weekly Quest #1: Sliding Sum Mastery

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

  • window size: An integer representing the size of the window.
  • tree heights: A list of integers representing the heights of trees in the forest.

Output

  • max sum: An integer representing the maximum sum of the heights of three adjacent trees.

Example

Input:

  • window size = 3
  • tree heights = [2, 4, 1, 5, 6, 3, 8, 2]

Output:

  • max sum = 17

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!

Rory Kemp

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

Mark Street

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

Conor McCarthy

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!

Alexander Unterrainer

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

要查看或添加评论,请登录

社区洞察

其他会员也浏览了