Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 10a082e

Browse files
author
Ram swaroop
committed
done (naive approach)
1 parent 93c459f commit 10a082e

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package me.ramswaroop.arrays;
2+
3+
import me.ramswaroop.common.MaxHeap;
4+
5+
import java.util.Arrays;
6+
7+
/**
8+
* Created by IntelliJ IDEA.
9+
*
10+
* @author: ramswaroop
11+
* @date: 9/3/15
12+
* @time: 9:21 PM
13+
*/
14+
public class MaxInAllSubArrays {
15+
16+
/**
17+
* Finds the maximum element in each and every sub-array
18+
* in {@param a} of size {@param k}.
19+
* <p/>
20+
* Time complexity: O(n^2)
21+
*
22+
* @param a
23+
* @param k
24+
*/
25+
public static int[] maxInAllSubArraysOfSizeKNaive(int[] a, int k) {
26+
int[] maxElements = new int[a.length - k + 1];
27+
int[] kElements;
28+
29+
for (int i = 0; i <= a.length - k; i++) {
30+
kElements = Arrays.copyOfRange(a, i, i + k);
31+
/**
32+
* maxHeapify() can't be used because to call maxHeapify() on i, left(i) and right (i) should
33+
* already satisfy the max heap property which isn't true in this case.
34+
*/
35+
MaxHeap.buildMaxHeap(kElements);
36+
maxElements[i] = kElements[0];
37+
}
38+
39+
return maxElements;
40+
}
41+
42+
public static void main(String a[]) {
43+
System.out.println(Arrays.toString(maxInAllSubArraysOfSizeKNaive(new int[]{1, 2, 3, 1, 4, 5, 2, 3, 6}, 3)));
44+
System.out.println(Arrays.toString(maxInAllSubArraysOfSizeKNaive(new int[]{8, 5, 10, 7, 9, 4, 15, 12, 90, 13}, 4)));
45+
}
46+
}

0 commit comments

Comments
 (0)