Learning GoLang: Maximum Gap

in #programming3 years ago
Given an integer array nums, return the maximum difference between two successive elements in its sorted form. If the array contains less than two elements, return 0.

Example 1:

Input: nums = [3,6,9,1]
Output: 3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the maximum difference 3.
Example 2:

Input: nums = [10]
Output: 0
Explanation: The array contains less than 2 elements, therefore return 0.

Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 109

GoLang Exercise as follows:

func maximumGap(nums []int) int {
    if len(nums) < 2 {
        return 0
    }
    var ans = 0
    sort.Ints(nums)
    for i := 1; i < len(nums); i ++ {
        ans = int(math.Max(float64(ans), float64(nums[i] - nums[i - 1])))
    }
    return ans
}

Time complexity is O(NLogN)

^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Thank you for reading ^^^^^^^^^^^^^^^

NEW! Following my Trail (Upvote or/and Downvote)

Follow me for topics of Algorithms, Blockchain and Cloud.
I am @justyy - a Steem Witness
https://steemyy.com

My contributions

Delegation Service

  1. Voting Algorithm Updated to Favor those High Delegations!
  • Delegate 1000 to justyy: Link
  • Delegate 5000 to justyy: Link
  • Delegate 10000 to justyy: Link

Support me

If you like my work, please:

  1. Delegate SP: https://steemyy.com/sp-delegate-form/?delegatee=justyy
  2. Vote @justyy as Witness: https://steemyy.com/witness-voting/?witness=justyy&action=approve
  3. Set @justyy as Proxy: https://steemyy.com/witness-voting/?witness=justyy&action=proxy
    Alternatively, you can vote witness or set proxy here: https://steemit.com/~witnesses

Sort:  

Yes... i am learning Go recently...

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.029
BTC 58127.19
ETH 2452.98
USDT 1.00
SBD 2.36