寻找最有利可图的范围(数学名称:"maximum subarray problem" 或 "maximum consecutive subsequence sum")

Looking for the most profitable range (mathematical names: "maximum subarray problem" or "maximum consecutive subsequence sum")

为了能够找到最大的 profitable 范围,我将我想要的最低值添加到我想要的最高值,然后我创建了一个 table 就像这个例子:

https://docs.google.com/spreadsheets/d/17zpapBeC5wYxyU6SjbqcbnV4_QP4gooxj0PxdCywDk0/edit?usp=sharing

单元格的公式示例:

00 之间:

=IFERROR(SUM(FILTER($B:$B,($A:$A<=D2)*($A:$A>=$E))))

510 之间:

=IFERROR(SUM(FILTER($B:$B,($A:$A<=D12)*($A:$A>=$J))))
=MAX(E2:O12)
Max Profit = £185.00

=INDEX(A1:O1,ARRAYFORMULA(MIN(IF(E2:O12=MAX(E2:O12),COLUMN(E2:O12)))))
Value Min for Max Profit = 4

=INDEX(D1:D12,ARRAYFORMULA(MAX(IF(E2:O12=MAX(E2:O12),ROW(E2:O12)))))
Value Max for Max Profit = 10

AB 中有数百个值¹时,这个 table 变得非常大和沉重,甚至像我当前的原始数据电子表格一样导致崩溃。

有什么方法可以仅使用一个公式或脚本代码来找到 Max Profit | Value Min for Max Profit | Value Max for Max Profit,而无需逐一计算每个范围,而无需使用数千个单元格,每个单元格都具有特定的公式?

备注:

数百个值¹ → 我的原始电子表格目前在 A 中包含 1471 行数据,结果在 B 中。因此,为了能够进行此分析,我需要在单元格中放入 2,163,841 公式,例如 =IFERROR(SUM(FILTER($B:$B,($A:$A<=D2)*($A:$A>=$E)))) 以创建 table 并找到最有利的 table 范围。

最大值:

=INDEX(MAX(IF(SEQUENCE(MAX(A:A)+1)>=SEQUENCE(1, MAX(A:A)+1), 
 SUMIF(SEQUENCE(MAX(A:A)+1), "<="&SEQUENCE(MAX(A:A)+1), B:B)* 
 SEQUENCE(1, MAX(A:A)+1, 1, )-QUERY(QUERY(
 (SEQUENCE(MAX(A:A)+1)<SEQUENCE(1, MAX(A:A)+1))*B1:B, 
 "select "&TEXTJOIN(",", 1, "sum(Col"&SEQUENCE(MAX(A:A)+1)&")")), 
 "offset 1", ), )))


最小值:

=INDEX(REGEXEXTRACT(MAX(IF(SEQUENCE(MAX(A:A)+1)>=SEQUENCE(1, MAX(A:A)+1), 
 SUMIF(SEQUENCE(MAX(A:A)+1), "<="&SEQUENCE(MAX(A:A)+1), B:B)* 
 SEQUENCE(1, MAX(A:A)+1, 1, )-QUERY(QUERY(
 (SEQUENCE(MAX(A:A)+1)<SEQUENCE(1, MAX(A:A)+1))*B1:B, 
 "select "&TEXTJOIN(",", 1, "sum(Col"&SEQUENCE(MAX(A:A)+1)&")")), 
 "offset 1", )+(SEQUENCE(1, MAX(A:A)+1)*10^-10)&9, )*1)&"", "0(\d+)9$")-1)

最大值:

=INDEX(REGEXEXTRACT(MAX(IF(SEQUENCE(MAX(A:A)+1)>=SEQUENCE(1, MAX(A:A)+1), 
 SUMIF(SEQUENCE(MAX(A:A)+1), "<="&SEQUENCE(MAX(A:A)+1), B:B)* 
 SEQUENCE(1, MAX(A:A)+1, 1, )-QUERY(QUERY(
 (SEQUENCE(MAX(A:A)+1)<SEQUENCE(1, MAX(A:A)+1))*B1:B, 
 "select "&TEXTJOIN(",", 1, "sum(Col"&SEQUENCE(MAX(A:A)+1)&")")), 
 "offset 1", )+(SEQUENCE(MAX(A:A)+1)*10^-10)&9, )*1)&"", "0(\d+)9$")-1)

更新:

=INDEX(TEXTJOIN(", ", 1, UNIQUE(FLATTEN(
 IF(IF(SEQUENCE(MAX(A:A)+1)>=SEQUENCE(1, MAX(A:A)+1), 
 SUMIF(SEQUENCE(MAX(A:A)+1), "<="&SEQUENCE(MAX(A:A)+1), B:B)* 
 SEQUENCE(1, MAX(A:A)+1, 1, )-QUERY(QUERY(
 (SEQUENCE(MAX(A:A)+1)<SEQUENCE(1, MAX(A:A)+1))*B1:B, 
 "select "&TEXTJOIN(",", 1, "sum(Col"&SEQUENCE(MAX(A:A)+1)&")")), 
 "offset 1", ), )=MAX(IF(SEQUENCE(MAX(A:A)+1)>=SEQUENCE(1, MAX(A:A)+1), 
 SUMIF(SEQUENCE(MAX(A:A)+1), "<="&SEQUENCE(MAX(A:A)+1), B:B)* 
 SEQUENCE(1, MAX(A:A)+1, 1, )-QUERY(QUERY(
 (SEQUENCE(MAX(A:A)+1)<SEQUENCE(1, MAX(A:A)+1))*B1:B, 
 "select "&TEXTJOIN(",", 1, "sum(Col"&SEQUENCE(MAX(A:A)+1)&")")), 
 "offset 1", ), )), SEQUENCE(1, MAX(A:A)+1, 0), )))))