Site icon R-bloggers

Slide, Scan, Sum — Find the largest

[This article was first published on Numbers around us - Medium, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Slide, Scan, Sum — Find the largest

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.


Slide, Scan, Sum — Find the largest was originally published in Numbers around us on Medium, where people are continuing the conversation by highlighting and responding to this story.

To leave a comment for the author, please follow the link and comment on their blog: Numbers around us - Medium.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version