Slide, Scan, Sum — Find the largest
Published in
2 min readNov 9, 2023
Excel BI’s Excel Challenge #320 — solved in R
Defining the Puzzle:
Current puzzle seems not hard, need few minutes to solve. Our host gave us sequence of numbers, both positive and negative and ask to find largest sum in contiguous positions. We can add as many numbers as we want as long they are one after another in this sequence.
Loading Data from Excel:
We need to load data and libraries.
library(tidyverse)
library(readxl)
library(data.table)
input = read_excel("Largest Sum.xlsx", range = "A1:A10")
Approach 1: Tidyverse with purrr
get_largest_cons_sum = function(numbers) {
max_len = length(numbers)
combs = expand.grid(start = 1:max_len, end = 1:max_len) %>%
filter(start < end)
sums = map2_dbl(combs$start, combs$end, ~ sum(numbers[.x:.y]))
res = max(sums)
return(res)
}
get_largest_cons_sum(input$Numbers)
#> [1] 9
Approach 2: Base R
get_largest_cons_sum_base = function(numbers) {
max_len = length(numbers)
combs = subset(expand.grid(start = 1:max_len, end = 1:max_len), start < end)
sums = mapply(function(s, e) sum(numbers[s:e]), combs$start, combs$end)
res = max(sums)
return(res)
}
get_largest_cons_sum_base(input$Numbers)
#> [1] 9
Approach 3: data.table
get_largest_cons_sum_dt = function(numbers) {
max_len = length(numbers)
DT = CJ(start = 1:max_len, end = 1:max_len)[start < end]
sums = DT[, .(sum = sum(numbers[start:end])), by = .(start, end)]
res = max(sums$sum)
return(res)
}
get_largest_cons_sum_dt(input$Numbers)
#> [1] 9
Validation:
All three functions returned value: 9 and that is the solution provided.
If you like my publications or have your own ways to solve those puzzles in R, Python or whatever tool you choose, let me know.