Skip to content

Instantly share code, notes, and snippets.

@bachiri
Created September 1, 2019 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bachiri/ad4fafb970807fb2aa779ef9af36d087 to your computer and use it in GitHub Desktop.
Save bachiri/ad4fafb970807fb2aa779ef9af36d087 to your computer and use it in GitHub Desktop.
239. Sliding Window Maximum/Leetcode
public class SlidingWindowMaximum {
public static void main(String[] args) {
int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
System.out.println("Maxs are " + Arrays.toString(maxSlidingWindow(nums, 3)));
}
public static int[] maxSlidingWindow(int[] nums, int k) {
List<Integer> result = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (i + k - 1 < nums.length) {
result.add(findmax(nums, i, i + k));
}
}
int[] arrayResult = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
arrayResult[i] = result.get(i);
}
return arrayResult;
}
private static Integer findmax(int[] nums, int start, int end) {
int max = Integer.MIN_VALUE;
for (int i = start; i < end; i++) {
max = Math.max(max, nums[i]);
}
return max;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment