2021-03-30

Maximum Gap

You are given an array of integers @N.

Write a script to display the maximum difference between two successive elements once the array is sorted.

If the array contains only 1 element then display 0.

#!/usr/bin/env tclsh
#
# You are given an array of integers @N.
# Write a script to display the maximum difference between 
# two successive elements once the array is sorted.
# If the array contains only 1 element then display 0.
#

if {$argc == 0} {
    exit
} elseif {$argc == 1} {
    puts "0"
    exit
}

set len [llength $argv]
set mylist [lsort -integer $argv]
set max 0
for {set count 1} {$count < $len} {incr count} {
    set prev [lindex $mylist [expr $count - 1]]
    set curr [lindex $mylist $count]

    set result [expr $curr - $prev]
    if {$result > $max} {
        set max $result
    }
}

puts $max

沒有留言: