Maximum gap | LeetCode : 164 | Tamil | Java

แชร์
ฝัง
  • เผยแพร่เมื่อ 14 พ.ย. 2024

ความคิดเห็น • 2

  • @MITHUNMKIT
    @MITHUNMKIT 10 หลายเดือนก่อน +1

    But linear time la poda solli irukanga,

    • @cse_maanavan
      @cse_maanavan  10 หลายเดือนก่อน +1

      But beginner kku konjam difficultaa irukkum bro... intha code check pannikonga bro.. It will be Work👍
      public class Solution {
      public int maximumGap(int[] nums) {
      int n = nums.length;
      if (n < 2) {
      return 0;
      }
      int minNum = Integer.MAX_VALUE;
      int maxNum = Integer.MIN_VALUE;
      for (int num : nums) {
      minNum = Math.min(minNum, num);
      maxNum = Math.max(maxNum, num);
      }
      int minGap = (int) Math.ceil((double) (maxNum - minNum) / (n - 1));
      int[] minBucket = new int[n - 1];
      int[] maxBucket = new int[n - 1];
      Arrays.fill(minBucket, Integer.MAX_VALUE);
      Arrays.fill(maxBucket, Integer.MIN_VALUE);
      for (int num : nums) {
      if (num == minNum || num == maxNum) {
      continue;
      }
      int index = (num - minNum) / minGap;
      minBucket[index] = Math.min(minBucket[index], num);
      maxBucket[index] = Math.max(maxBucket[index], num);
      }
      int maxGap = 0;
      int prevMax = minNum;
      for (int i = 0; i < n - 1; i++) {
      if (minBucket[i] == Integer.MAX_VALUE && maxBucket[i] == Integer.MIN_VALUE) {
      continue;
      }
      maxGap = Math.max(maxGap, minBucket[i] - (prevMax = maxBucket[i]));
      }
      return Math.max(maxGap, maxNum - prevMax);
      }
      }