diff --git a/src/com/hong/www/A1438.java b/src/com/hong/www/A1438.java new file mode 100644 index 0000000..c5b6d66 --- /dev/null +++ b/src/com/hong/www/A1438.java @@ -0,0 +1,40 @@ +package com.hong.www; + +import java.util.*; + +public class A1438 { + public int longestSubarray(int[] nums, int limit) { + int fina = 0; + int left = 0; + int right = 0; + //PriorityQueue temp1 = new PriorityQueue<>((a, b) -> b - a); + //PriorityQueue temp2 = new PriorityQueue<>((a, b) -> a - b); + TreeMap map = new TreeMap<>(); + while (right < nums.length) { + //temp1.offer(nums[right]); + //temp2.offer(nums[right]); + //int max = temp1.peek(); + //int min = temp2.peek(); + map.put(nums[right], map.getOrDefault(nums[right], 0) + 1); + int max = map.lastKey(); + int min = map.firstKey(); + + while (max - min > limit && left < right) { + //temp1.remove(nums[left]); + //temp2.remove(nums[left]); + map.put(nums[left], map.get(nums[left]) - 1); + if (map.get(nums[left]) == 0) { + map.remove(nums[left]); + } + left++; + max = map.lastKey(); + min = map.firstKey(); + } + if(right-left>fina){ + fina=right-left; + } + right++; + } + return fina+1; + } +}