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 largest number n positions away from n

A sequel to this question.

Task

Given an array of positive integers, find the largest element k for which:

There exists some positive integer distance n, so that the element in the array located n places to the left or right from k equals n.

The array is guaranteed to contain at least one element satisfying this condition.

The shortest code (in bytes) wins. You may choose whichever I/O format you like.

Example

Given the input

[4, 6, 7, 9, 3, 6, 5, 7, 2]

The eligible values are:

  • The 4, as there is a 7 located 7 positions to its right
  • The first 6, as there is a 3 located 3 positions to its right
  • The 3, as there is a 4 located 4 positions to its left
  • The 5, as there is a 2 located 2 positions to its right
  • The second 7, as there is a 3 located 3 positions to its left.

Of these values, the largest is 7.

Test cases

[1, 13] → 13
[2, 9, 8, 3, 72, 2] → 8
[5, 28, 14, 5, 6, 3, 4, 7] → 14
[1, 3, 5, 15, 4, 1, 2, 6, 7, 7] → 7
[5, 1, 3, 5, 2, 5, 5, 8, 5, 1, 5, 1, 2, 3] → 5
[5, 12, 2, 5, 4, 7, 3, 3, 6, 2, 10, 5, 5, 5, 4, 1, 8, 5] → 10

Answer*

Draft saved
Draft discarded
Cancel
4
  • \$\begingroup\$ you can use .map instead of .each \$\endgroup\$ Commented Sep 23, 2016 at 20:58
  • \$\begingroup\$ also (x) if (y) can be replaced with (y)&&(x) \$\endgroup\$ Commented Sep 23, 2016 at 20:59
  • \$\begingroup\$ You can use a<<b instead of a+=[b] \$\endgroup\$ Commented Sep 24, 2016 at 7:02
  • \$\begingroup\$ @Sherlock9 I forgot about << . Using a+=[b] didn't work with Cyoce's suggestion using &&. Now it does, thanks! \$\endgroup\$ Commented Sep 24, 2016 at 22:39

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