Created
September 1, 2019 08:55
-
-
Save bachiri/ad4fafb970807fb2aa779ef9af36d087 to your computer and use it in GitHub Desktop.
239. Sliding Window Maximum/Leetcode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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