[Question]
  [
This problem is "inspired" from a question that was originally asked on [Quora](https://www.quora.com/unanswered/How-should-one-find-the-maximum-deviation-from-a-given-number-of-consecutive-integers) (not for code golfing). I just want to make it a challenge for you guys (and my first problem submission here). 
Given an array of integer elements `v` and an integer `d` (we assume that d is lower or equal to the array's length), consider all the sequences of `d` consecutive elements in the array. For each sequence, compute the difference between the maximum and minimum value of the elements in that sequence and name it the deviation.
Your task is to write a program or function that computes the maximum value among all deviations of all the sequences considered above, and return or output that value.
Worked-through Example: 
```
v: (6,9,4,7,4,1)
d: 3
The sequences of length 3 are:
6,9,4 with deviation 5
9,4,7 with deviation 5
4,7,4 with deviation 3
7,4,1 with deviation 6
Thus the maximal deviation is 6, so the output is 6.
```
This is code golf, so the shortest answer in bytes wins.
  
[Answer]
# Dyalog APL, 7 bytes
```
⌈/⌈/-⌊/
```
Test it on [TryAPL](http://tryapl.org/?a=f%u2190%u2308/%u2308/-%u230A/%20%u22C4%203%20f%206%209%204%207%204%201&run).
### How it works
```
⌈/⌈/-⌊/  Dyadic chain. Left argument: d. Right argument: v
     ⌊/  Reduce v by d-wise minimum, yielding the minima of all slices of length d.
  ⌈/     Reduce v by d-wise maximum, yielding the maxima of all slices of length d.
    -    Subtract, yielding the ranges of all slices of length d.
⌈/       Take the maximum.
```
[Answer]
## JavaScript (ES6), 73 bytes
```
with(Math)(v,d)=>max(...v.map((a,i)=>max(...a=v.slice(i,i+d))-min(...a)))
```
[Answer]
# Python, 60 bytes
Saving 5 bytes thanks to Neil
```
f=lambda v,d:v and max(max(v[:d])-min(v[:d]),f(v[1:],d))or 0
```
My first recursive lambda!
Usage:
```
print f([6,9,4,7,4,1], 3)
```
[Answer]
# Perl, 48 bytes
Includes +5 for `-0pi`
Give the width after the `-i` option, give the elements as separate lines on STDIN:
```
perl -0pi3 -e '/(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F'
6
9
4
7
4
1
^D
```
Just the code:
```
/(^.*\n){1,$^I}(?{\$F[abs$1-$&]})\A/m;$_=$#F
```
(use a literal `\n` for the claimed score)
[Answer]
# R, ~~63~~ ~~62~~ 56 bytes
Billywob has already provided a great [R answer using only the base functions](https://codegolf.stackexchange.com/a/96926/59052). However, I wanted to see if an alternative approach was possible, perhaps using some of R's extensive packages. There's a nice function `rollapply` in the `zoo` package designed to apply a function to a rolling window of an array, so that fits our purposes well. We use `rollapply` to find the `max` of each window, and we use it again to find the `min` of each window. Then we take the difference between the maxes and mins, which gives us the deviation for each window, and then return the `max` of those.
```
function(v,d)max((r=zoo::rollapply)(v,d,max)-r(v,d,min))
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~13~~ 7 bytes
```
▲m§-▼▲X
```
[Try it online!](https://tio.run/##yygtzv7//9G0TbmHlus@mrYHyIr4//@/8f9oMx1LHRMdcyA2jAUA "Husk – Try It Online")
-6 bytes from Jo King.
## Explanation
```
▲m§-▼▲X Slices of length n
 m      map to
  §-    difference between
    ▼▲  min and max
▲       take the maximum of that
   
```
[Answer]
# R, 80  77 bytes bytes
Edit: Saved 3 bytes thanks to @rturnbull
```
function(s,d)max(sapply(d:sum(1|s)-d+1,function(i)diff(range(s[i:(i+d-1)]))))
```
[Answer]
# Mathematica, ~~41~~ 37 bytes
```
Max[MovingMap[MinMax,#,#2-1].{-1,1}]&
```
[Answer]
## PowerShell v2+, 68 bytes
```
param($v,$d)($v|%{($x=$v[$i..($i+++$d-1)]|sort)[-1]-$x[0]}|sort)[-1]
```
Iterative solution. Loops through `$v`, but really we're just using that as a counter rather than actually going through the values. Each iteration, we're slicing `$v` by `$i..($i+++$d-1)`, where `$i` defaults to `0`. We `|sort` those elements, and store the result into `$x`. Then we take the biggest `[-1]` and subtract the smallest `[0]`. We then `|sort` those results and take the biggest `[-1]` of that. That number is left on the pipeline and output is implicit.
### Examples
```
PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(6,9,4,7,4,1) 3
6
PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(1,2,3,4,5,6) 3
2
PS C:\Tools\Scripts\golfing> .\find-the-maximum-deviation.ps1 @(7,2,3,4,5,6) 3
5
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes
Uses [CP-1252](http://www.cp1252.com) encoding.
```
Œù€{øÀ`-ÄZ
```
[Try it online!](http://05ab1e.tryitonline.net/#code=xZLDueKCrHvDuMOAYC3DhFo&input=WzYsOSw0LDcsNCwxXQoz)
**Explanation**
```
Œ              # sublists of v
 ù             # of length d
  €{           # sort each
    ø          # zip
     À         # rotate left (last 2 lists will be largest and smallest)
      `        # flatten (lists with smallest and largest item will be on top)
       -       # subtract largest from smallest
        Ä      # take absolute value (as we will have negatives after the previous step)
         Z     # take the largest
```
[Answer]
# Ruby, 45 bytes
```
->a,d{a.each_cons(d).map{|b|b.max-b.min}.max}
```
I feel like this could be a lot better.
[Answer]
# Scala, 48 bytes
```
(_:Seq[Int])sliding(_:Int)map(s=>s.max-s.min)max
```
Ungolfed:
```
(a:Seq[Int],d:Int)=>a.sliding(d).map(s=>s.max-s.min).max
```
Explanation:
```
(_:Seq[Int])   //define a function with a seq of ints as an argument
sliding(_:Int) //get the sequences with the length of an int argument
map(s=>        //map each sequence
  s.max-s.min    //to its deviation
)max           //and take the maximum value
```
[Answer]
# Java 8, 140 128
Shaved a bunch off, in part thanks to VTCAKAVSMoACE.
```
int l(int[]a,int d){int x=0,i=0,f,j,k;for(;i<=a.length-d;i++)for(j=i;j<i+d;j++)for(k=i;k<i+d;)x=(f=a[j]-a[k++])>x?f:x;return x;}
```
Ungolfed
```
int l(int[]a,int d){
    int x=0,i=0,f,j,k;
    for(;i<=a.length-d;i++)
        for(j=i;j<i+d;j++)
            for(k=i;k<i+d;)
                x=(f=a[j]-a[k++])>x?f:x;
    return x;
}
```
[Answer]
# [Factor](https://factorcode.org/) + `math.statistics`, 32 bytes
```
[ clump [ range ] map supremum ]
```
[Try it online!](https://tio.run/##DcwxCgIxEAXQfk/xT7AgiqIeQGxsxGrZIgxjDCbZ7MykEPHsMcVr39ORLdIe9@vtcsKbJXNEETb7FAnZ4GWpJWSP5Ow1qjkLaoEUymvlTKw4D8MXexyxw6Hb4Idtm0CxpoIJ4rJnzD0o0NrvVBPmRi5GjO0P "Factor – Try It Online")
* `clump` Get the windows of [first input] of length [second input]
* `[ range ] map` Map each window to its 'deviation' (which Factor calls `range`)
* `supremum` Maximum element
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 70 bytes
```
(0..(-$d+$v.count)|%{$s=$v[$_..($_+$d-1)]|sort;$s[-1]-$s[0]}|sort)[-1]
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvUqZgq@CgYaZjqWOiYw7EhppcKilAMeP/GgZ6ehq6KinaKmV6yfmleSWaNarVKsW2KmXRKvFAKZV4bZUUXUPN2Jri/KISa5XiaF3DWF0gZRBbCxbSBAn8//8fAA "PowerShell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ŒIùεW-}à
```
Inputs in the order \$v,d\$.
[Try it online.](https://tio.run/##yy9OTMpM/f//6CTPwzvPbQ3XrT284P//aDMdSx0THXMgNozlMgYA)
**Explanation:**
```
Œ       # Get all sublists of the first (implicit) input-list `v`
 Iù     # Only keep those with a length equal to the second input-integer `d`
   ε    # Map over each d-sized sublist:
    W   #  Push the minimum of the current sublist (without popping the list)
     -  #  Subtract this minimum from each value in the list
   }à   # After the map: pop and push the flattened maximum
        # (which is output implicitly as result)
```
The map `εW-}` could alternatively be `D€ß-` for a vectorized subtraction.
[Answer]
# MATLAB with Statistics and Image Processing Toolboxes, 33 bytes
```
@(v,d)max(range(im2col(v,[1 d])))
```
This defines an anonymous function. Example use:
```
>> f = @(v,d)max(range(im2col(v,[1 d])));
>> f([6,9,4,7,4,1], 3)
ans =
     6
```
You can also [try it on Octave at Ideone](http://ideone.com/Dfi7Ch) (but Octave, unlike Matlab, requires explicitly loading the image package).
### Explanation
```
im2col(v,[1 d]))   % Takes overlapping blocks of size d from v, and arranges them as
                   % columns of a matrix
range(...)         % Maximum minus minimum of each column. Gives a row vector
max(...)           % Maximum of the above row vector
```
[Answer]
# Java 7,159 bytes
Java = expensive(i know it can be golfed much more)
```
int c(int[]a,int d){int[]b=new int[d];int i,j,s=0;for(i=-1;i<a.length-d;){for(j=++i;j<i+d;)b[i+d-1-j]=a[j++];Arrays.sort(b);s=(j=b[d-1]-b[0])>s?j:s;}return s;}
```
# Ungolfed
```
static int c ( int []a , int d){
    int []b = new int[ d ];
    int i , j , s = 0 ;
    for ( i = -1 ; i < a.length - d ;) {
        for ( j = ++i ; j < i + d ;)
        b[ i + d - 1 - j ] = a[ j++ ] ;
        Arrays.sort( b ) ;
        s = ( j = b[ d - 1 ] - b[ 0 ] ) > s ? j : s ;
    }
    return s ;
    }
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 10 bytes
```
YCS5LY)dX>
```
[Try it online!](http://matl.tryitonline.net/#code=WUNTNUxZKWRYPg&input=WzYsOSw0LDcsNCwxXQoz)
### Explanation
Consider inputs [6,9,4,7,4,1], 3 as an example.
```
       % Implicitly take the two inputs: v, d
       % STACK: [6,9,4,7,4,1], 3
YC     % Matrix of overlapping d-blocks of v
       % STACK: [6 9 4 7
                 9 4 7 4
                 4 7 4 1]
S      % Sort each column
       % STACK: [4 4 4 1
                 6 7 4 4
                 9 9 7 7]
5LY)   % Keep first and last rows
       % STACK: [4 4 4 1
                 9 9 7 7]
d      % Differences along each column
       % STACK: [5 5 3 6]
X>     % Maximum
       % STACK: 6
       % Implicitly display
```
[Answer]
# PHP, ~~89~~ 87 bytes
```
for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;
```
Not particularly clever or pretty but it works. Use like:
```
php -r "for($i=1;$r=array_slice($argv,++$i,$argv[1]);$d=max($r)-min($r))$o=$d>$o?$d:$o;echo+$o;" 3 6 9 4 7 1
```
for `v`=`6,9,4,7,4,1`, `d`=`3`
Edit: 2 bytes saved thanks to Jörg Hülsermann
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṡµṂ€ạṀ€Ṁ
```
[Try it online!](https://tio.run/nexus/jelly#@/9w58JDWx/ubHrUtObhroUPdzaAGDsb/v//b6ZjqWOiYw7Ehv@NAQ "Jelly – TIO Nexus")
Uses the same algorithm as Dyalog APL, but I figured this myself before looking at it.
Explanation:
```
ṡµṂ€ạṀ€Ṁ ḷ“Main link. Arguments: v d.”
ṡ        ḷ“Overlapping sublists of x of length y.”
 µ       ḷ“Start a new monadic chain.”
  Ṃ€ạṀ€  ḷ“Find the deviation of each of the elements of x.”
       Ṁ ḷ“Take the maximum of x.”
```
Note: `x`, `y` are left, right arguments respectively.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
s₎ᶠ⟨⌉-⌋⟩ᵐ⌉
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/hRU9/DbQsezV/xqKdT91FP96P5Kx9unQDk/P8fHW2mY6ljomMOxIaxOsax/6MA "Brachylog – Try It Online")
[Answer]
# [Arturo](https://arturo-lang.io), 59 bytes
```
$[a,n][max map 0..-size a n'x[z:a\[x..x+n-1](max z)-min z]]
```
[Try it](http://arturo-lang.io/playground?VCYkUQ)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ãV mÍ®Ì-ZÎÃÍ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=41Ygbc2uzC1azsPN&input=WzYsOSw0LDcsNCwxXSAz)
```
ãV     # subsequences of length V
mÍ     # sort each, ascending
®Ì-ZÎÃ # map each to last - first
Í      # sort, ascending
# -h flag prints the last element 
```
[Answer]
# [Desmos](https://www.desmos.com), ~~62~~ 58 bytes
```
r=v[i-d+1...i]
f(v,d)=[r.max-r.minfori=[d...v.length]].max
```
[Try it on Desmos!](https://www.desmos.com/calculator/bnvread4ok)
  
-4 bytes thanks to [Aiden Chow](https://codegolf.stackexchange.com/users/96039/aiden-chow)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `G`, 12 bytes
```
ÞS'L⁰=;ƛG$g-
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJHIiwiIiwiw55TJ0zigbA9O8abRyRnLSIsIiIsIjYsOSw0LDcsNCwxXG4zIl0=)
#### Explanation
```
ÞS'L⁰=;ƛG$g-  # Implicit input
ÞS            # All sublists of the first input
  '   ;       # Filtered by the following:
   L          #  The length of the sublist
    ⁰=        #  Equals the second input
       ƛ      # Map over the filtered list:
        G     #  Push the maximum of the sublist
         $g   #  Swap and push the minimum
           -  #  Subtract to find the deviation
              # G flag gets the maximum of this list
              # Implicit output
```
[Answer]
# [Uiua](https://uiua.org), 10 [bytes](https://codegolf.stackexchange.com/a/265917/97916)
```
/↥-⊃/↧/↥⍉◫
```
[Try it!](https://uiua.org/pad?src=0_3_1__ZiDihpAgL-KGpS3iioMv4oanL-KGpeKNieKXqwoKZiAzIFs2IDkgNCA3IDQgMV0K)
```
/↥-⊃/↧/↥⍉◫
         ◫  # windows
        ⍉   # transpose
   ⊃/↧/↥    # maxes and mins of each column
  -         # subtract
/↥          # maximum
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 17 bytes
```
q~ew{$)\(\;-}%:e>
```
(Also `q~ew:$z)\(\;.-:e>`)
[Try it online!](http://cjam.tryitonline.net/#code=cX5ld3skKVwoXDstfSU6ZT4&input=WzYgOSA0IDcgNCAxXQoz)
### Explanation
```
q~                   e# Read the two inputs. Evaluate
  ew                 e# Overlapping blocks
    {       }%       e# For each block
     $               e# Sort
      )              e# Get last element (that is, maximum)
       \(            e# Swap, get first element (minimum)
         \;          e# Swap, delete rest of the block
           -         e# Subtract (maximum minus minimum)
              :e>    e# Maximum of array
```
[Answer]
## Haskell, 56 bytes
```
_#[]=0 
d#l|m<-take d l=max(maximum m-minimum m)$d#tail l
```
Usage example: `3 # [6,9,4,7,4,1]` -> `6`.
Considering ranges less than `d` doesn't change the overall maximum, so we can run `take d` down to the very end of the list (i.e. also include the ranges with the last `d-1`, `d-2`, ... `0` elements). The recursion stops with the empty list where we set the deviation to `0`. 
[Answer]
# [Actually](http://github.com/Mego/Seriously), 13 bytes
```
╗╜@V`;m@M-`MM
```
[Try it online!](http://actually.tryitonline.net/#code=4pWX4pWcQFZgO21ATS1gTU0&input=WzYsOSw0LDcsNCwxXQoz)
-6 bytes from the observation in nimi's [Haskell answer](https://codegolf.stackexchange.com/a/97003/45941), that slices shorter than `d` don't affect the maximum deviation.
Explanation:
```
╗╜@V`;m@M-`MM
╗              store d in register 0
 ╜@            push d, swap so v is on top
   V           push all slices of v whose length is in [1, d]
    `;m@M-`M   map (for each slice):
     ;m@M-       get minimum and maximum, subtract min from max
           M  get maximum of list of deviations
```
]