This file contains 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
// Appproach #1 - T O(n log n). | |
public class Solution { | |
/** | |
* @param A: the array A | |
* @return: return the maximum profit | |
*/ | |
public int getAns(int[] A) { | |
// handle corner cases | |
if (A == null || A.length == 0) { | |
return 0; | |
} | |
int profit = 0; | |
Queue<Integer> pq = new PriorityQueue<>((o1, o2) -> o1 - o2); | |
for (int a : A) { | |
if (!pq.isEmpty() && pq.peek() < a) { | |
// greedy: found business proposition | |
profit += a - pq.poll(); | |
// correctness: in case you will find even better business proposition | |
pq.offer(a); | |
} | |
pq.offer(a); | |
} | |
return profit; | |
} | |
} |
No comments:
Post a Comment