Given an unsorted array, find the maximum difference between the successive elements in its sorted form.
Return 0 if the array contains less than 2 elements.
Return 0 if the array contains less than 2 elements.
Example 1:
Input: [3,6,9,1]
Output: 3
Approach
Java
import java.util.Arrays;public class MaximumGap {public static void main(String[] args) {int[] nums = { 3, 6, 9, 1 };System.out.println(maximumGap(nums));}static int maximumGap(int[] nums) {// sort the arrayArrays.sort(nums);if (nums.length < 2)return 0;int ans = Integer.MIN_VALUE;for (int i = 1; i < nums.length; i++) {ans = Math.max(ans, nums[i] - nums[i - 1]);}return ans;}}
C++
#include <bits/stdc++.h>using namespace std;int maximumGap(vector<int> &nums){//sort the arraysort(nums.begin(), nums.end());if (nums.size() < 2)return 0;int ans = INT_MIN;for (int i = 1; i < nums.size(); i++){ans = max(ans, nums[i] - nums[i - 1]);}return ans;}int main(){vector<int> nums = {3, 6, 9, 1};cout << maximumGap(nums);return 0;}
No comments:
Post a Comment