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

Commit 76eb3d7

Browse files
committed
Arrays & Heaps
1 parent f0f66b9 commit 76eb3d7

6 files changed

+3111
-0
lines changed

src/main/java/com/arrays/MaxSumSubArray_KadaneAlgo_DynamicProgram.html

Lines changed: 2919 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package com.arrays;
2+
/*
3+
4+
Dynamic programming solves a problem by dividing it into smaller subproblems. This is very similar to the divide-and-conquer algorithm solving technique.
5+
The major difference, however, is that dynamic programming solves a subproblem only once.
6+
It then stores the result of this subproblem and later reuses this result to solve other related subproblems. This process is known as memoization.
7+
8+
Dynamic programming builds solutions from the bottom up by breaking each problem down into smaller,
9+
problems that you solve first. Recursion also breaks problems down into subproblems but does this from
10+
the top down.
11+
One advantage of dynamic programming over recursion is that it prevents possible duplicate solutions of the same subproblem,
12+
which uses less CPUs and generally makes your code run faster.
13+
14+
Complexity of finding largest sum subarray in an array is O(N) in time and O(1) in space.
15+
16+
*/
17+
18+
public class MaxSumSubArray_KadaneAlgo_DynamicProgram {
19+
20+
public static void main(String[] args) {
21+
22+
int[] arr = {-1, 3, -5, 4, 6, -1, 2, -7, 3, -3};
23+
24+
int[] result = findMaxSumIndex(arr);
25+
System.out.println("start index :" + result[0]);
26+
System.out.println("End index :" + result[1]);
27+
System.out.println("Sum :" + result[2]);
28+
29+
}
30+
31+
private static int[] findMaxSumIndex(int[] arr) {
32+
int[] result = new int[3];
33+
int maxSumTillNow = Integer.MIN_VALUE;
34+
35+
int tempStartIndex = 0;
36+
int tempSum = 0;
37+
38+
for (int i = 0; i < arr.length; i++) {
39+
tempSum = tempSum + arr[i];
40+
41+
if (tempSum > maxSumTillNow) {
42+
maxSumTillNow = tempSum;
43+
result[0] = tempStartIndex;
44+
result[1] = i;
45+
result[2] = maxSumTillNow;
46+
}
47+
48+
//Important Condition to reset
49+
if (tempSum < 0) {
50+
tempSum = 0;
51+
tempStartIndex = i + 1;
52+
}
53+
}
54+
return result;
55+
}
56+
}
57+
58+

src/main/java/com/arrays/SortArrayOf0s1s2s_DutchNationalFlagAlgo.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package com.arrays;
22

33
/*
4+
Dutch National Flag Algorithm, or 3-way Partitioning
5+
46
Sort an array of 0s, 1s and 2s
57
Given an array A[] consisting 0s, 1s and 2s.
68
The task is to write a function that sorts the given array.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package com.arrays;
2+
3+
/**
4+
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/
5+
* Approach-3
6+
*
7+
* we can simply go on crawling over the slope and keep on adding the profit obtained
8+
* from every consecutive transaction.
9+
*
10+
* we can directly keep on adding the difference between the consecutive numbers of the array
11+
* if the second number is larger than the first one, and at the total sum we obtain will be the maximum profit.
12+
*
13+
* Since there is no transaction limit, we just calculate max amount of profit, which is
14+
* "any price raise is profit".
15+
*
16+
* From the above graph, we can observe that the sum A+B+C is equal to the difference D
17+
* corresponding to the difference between the heights of the consecutive peak and valley.
18+
*
19+
* Example 1:
20+
*
21+
* Input: [7,1,5,3,6,4]
22+
* Output: 7
23+
* Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
24+
* Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
25+
*
26+
* Complexity Analysis
27+
*
28+
* Time complexity : O(n). Single pass.
29+
*
30+
* Space complexity: O(1). Constant space needed.
31+
*/
32+
public class StockBuySellToMaximizeProfit_PeakValleyApproach {
33+
34+
public static int maxProfit(int[] prices) {
35+
int maxprofit = 0;
36+
for (int i = 1; i < prices.length; i++) {
37+
if (prices[i] > prices[i - 1])
38+
maxprofit += prices[i] - prices[i - 1];
39+
}
40+
return maxprofit;
41+
}
42+
43+
public static void main (String args[]){
44+
int[] price = {100,60,120,110,90,200};
45+
int maxProfit= maxProfit(price);
46+
System.out.println(maxProfit);
47+
48+
}
49+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.heaps;
2+
3+
import java.util.PriorityQueue;
4+
5+
/*
6+
7+
Link to priority Queue -
8+
https://onedrive.live.com/redir?resid=26052E8C3C647484%21105&page=Edit&wd=target%28Queue.one%7C71d394a6-f4c4-41dd-b56a-e1878e78a88a%2FPriorityQueue%7C27bf58ff-75e1-4c3a-aa71-2823e1ff846b%2F%29
9+
10+
An Efficient Solution is to use Min Heap of size k to store k largest elements of the stream.
11+
The k’th largest element is always at root and can be found in O(1) time.
12+
13+
Time complexity of finding the k’th largest element is O(Logk).
14+
15+
*/
16+
public class KthLargestElement {
17+
18+
public static int findKthLargest(int arr[], int k) {
19+
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
20+
for (int num : arr) {
21+
minHeap.add(num);
22+
if (minHeap.size() > k) {
23+
24+
//this will remove the element from root since its minHeap it will remove minimum element.
25+
//this will rearrange the elements back in proper heap with min element on root.
26+
minHeap.remove();
27+
}
28+
}
29+
return minHeap.remove();
30+
}
31+
32+
public static void main(String args[]) {
33+
int arr[] = {10, 70, 20, 30, 50, 80};
34+
int result = findKthLargest(arr, 2);
35+
System.out.println(result);
36+
}
37+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.heaps;
2+
3+
import java.util.PriorityQueue;
4+
5+
6+
/*
7+
8+
Example:
9+
10+
int[] A = { 1, 2, 10, 20, 40, 32, 44, 51, 6 };
11+
12+
K=4. 4th smallest element in given array: 10
13+
14+
Approach: (Kth Smallest Element)
15+
Use min-Heap. (Click here to read about Priority Queue).
16+
Insert all the elements in the Priority Queue.
17+
Extract K elements from the priority queue.
18+
The last element (kth) extracted with be the kth smallest element in the array.
19+
20+
Link to priority Queue -
21+
https://onedrive.live.com/redir?resid=26052E8C3C647484%21105&page=Edit&wd=target%28Queue.one%7C71d394a6-f4c4-41dd-b56a-e1878e78a88a%2FPriorityQueue%7C27bf58ff-75e1-4c3a-aa71-2823e1ff846b%2F%29
22+
23+
24+
*/
25+
public class KthSmallestElement {
26+
27+
public static int findKthSmallest(int arr[], int k) {
28+
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
29+
for (int num : arr) {
30+
minHeap.add(num);
31+
}
32+
int n = -1;
33+
while(k>0){
34+
n = minHeap.poll();
35+
k--;
36+
}
37+
38+
return n;
39+
}
40+
41+
public static void main(String args[]) {
42+
int arr[] = {10, 70, 20, 30, 50, 80};
43+
int result = findKthSmallest(arr, 5);
44+
System.out.println(result);
45+
}
46+
}

0 commit comments

Comments
 (0)