Problem of the Day
A new programming or logic puzzle every Mon-Fri

Largest Difference

Given an array of integers print out the largest difference between two adjacent numbers. For the array [4,8,3], 8-3 would be the largest difference.

Permalink: http://problemotd.com/problem/largest-difference/

Comments:

  • Anonymous - 10 years, 1 month ago

    def largest_difference(lst):
        return max(abs(a-b) for a, b in zip(lst, lst[1:]))
    

    reply permalink

  • Anon - 10 years, 1 month ago

    Java:

      public int highestDiff (int[] array) {
        int highest = 0;
        for (int i : array) {
          if (i > highest) {
            highest = i;
          }
        }
    
        int lowest = highest;
        for (int j : array) {
          if (j < lowest) {
            lowest = j;
          }
        }
    
        return highest - lowest;
      }
    

    reply permalink

  • Anonymous - 10 years, 1 month ago

    C#

        public static int LargestDifference(int[] arr)
        {
            int difference = 0;
            for(int i = 0; i < arr.Length -1; i++)
                difference = Math.Abs(arr[i] - arr[i + 1]) > difference ? Math.Abs(arr[i] - arr[i + 1]) : difference;
            return difference;
        }
    

    reply permalink

  • Jordan - 10 years, 1 month ago

    Here's the javascript version of this!

    var array = [4, 10, 20, 30, 50, 67, 4, 20]; var len = array.length; var high = 0;

    for (i = 0; i < len || function(){ alert(high); return false;}(); i += 2){

    largest_diff(array[i], array[i+1]);
    

    }

    function largest_diff(x, y){

    var sum = x - y;
    
    var absolute = Math.abs(sum);
    
    if(absolute > high){
           high = absolute;
    }
    
    return high;
    

    }

    jsfiddle here:

    http://jsfiddle.net/rryw8abo/9/

    reply permalink

  • Jordan - 10 years, 1 month ago

    Javascript:

    http://jsfiddle.net/rryw8abo/10/

    reply permalink

  • Driphter - 10 years, 1 month ago

    Clojure!

    (defn max-adj-diff [s]
      (->> (map - s (next s))
           (map #(Math/abs %))
           (apply max)))
    

    C#!

    int MaxAdjacentDifference(int[] arr)
    {
        return arr.Zip(arr.Skip(1), (x, y) => x - y)
                  .Max(x => Math.Abs(x));
    }
    

    reply permalink

  • Anonymous - 10 years, 1 month ago

    Cool did not know about the zip method in c#

    reply permalink

  • Nick - 10 years, 1 month ago

    Javascript:

    var difference = function(array) {
        array = array || [];
        return Math.max.apply(null, array.map(function(el, idx) {
            return Math.abs((el - array[idx + 1])) || 0;
        }));
    }
    

    reply permalink

Content curated by @MaxBurstein