Skip to main content
We’ve updated our Terms of Service. A new AI Addendum clarifies how Stack Overflow utilizes AI interactions.
Code Golf

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Find the greatest line

You will be given a 2-D array A of integers, and a length N. Your task is to find within the array the straight line (horizontal, vertical or diagonal) of N elements that yields the highest total sum, and return that sum.

Example

 N = 3, A = 
 3 3 7 9 3
 2 2 10 4 1
 7 7 2 5 0
 2 1 4 1 3

This array has 34 valid lines, including

 Vertical
 [3] 3 7 9 3
 [2] 2 10 4 1
 [7] 7 2 5 0
 2 1 4 1 3 [3,2,7] = 12
 Horizontal
 3 3 7 9 3
 2 2 10 4 1
 7 7 [2] [5] [0]
 2 1 4 1 3 [2,5,0] = 7
 Diagonal
 3 3 [7] 9 3
 2 2 10 [4] 1
 7 7 2 5 [0]
 2 1 4 1 3 [7,4,0] = 11

The maximum line is

 3 3 7 [9] 3
 2 2 [10] 4 1
 7 [7] 2 5 0
 2 1 4 1 3 [7,10,9] = 26

Note: lines may not wrap around the edges of the array.

Inputs

  • A X by Y 2-D array A, with X,Y> 0. Each element of the array contains an integer value which may be positive, zero or negative. You may accept this array in an alternative format (e.g. list of 1-D arrays) if you wish.
  • A single, positive integer N, no greater than max(X,Y).

Output

  • A single value representing the maximal line sum that can be found in the array. Note that you do not need to provide the individual elements of that line or where it is located.

Test cases

N = 4, A = 
-88 4 -26 14 -90
-48 17 -45 -70 85
 22 -52 87 -23 22
-20 -68 -51 -61 41
Output = 58
N = 4, A =
 9 4 14 7
 6 15 1 12
 3 10 8 13
16 5 11 2
Output = 34
N = 1, A = 
 -2
Output = -2
N = 3, A =
1 2 3 4 5
Output = 12
N = 3, A = 
-10 -5 4
 -3 0 -7
-11 -3 -2
Output = -5 

Answer*

Draft saved
Draft discarded
Cancel
3
  • \$\begingroup\$ Some optimizations: Diagonal[s,#] to s~Diagonal~#, and {{Transpose@#,#2},{Reverse@#,#2}} to {#|#2,Reverse@#|#2}. (The unprintable is U+F3C7 = \[Transpose]; TIO doesn't seem to like this, though. Alternative: {Transpose@#|#2,Reverse@#|#2}) \$\endgroup\$ Commented Oct 16, 2017 at 20:56
  • \$\begingroup\$ @JungHwanMin It's not TIO's fault, Mathematica on TIO is run in script mode, which only support ASCII. You need to type \[Transpose] or \:f3c7 (at least the latter is shorter than Thread@) However if the answer is Mathematica REPL (not Mathematica script) you can assume the 3-byte solution. \$\endgroup\$ Commented Oct 17, 2017 at 1:06
  • \$\begingroup\$ @user202729 Thanks, didn't know! \$\endgroup\$ Commented Oct 17, 2017 at 1:19

AltStyle によって変換されたページ (->オリジナル) /