Skip to content

Commit 873dde6

Browse files
ThanhNITjavadev
authored andcommitted
Added tasks 2034, 2035, 2037.
1 parent be1fde5 commit 873dde6

File tree

9 files changed

+413
-0
lines changed

9 files changed

+413
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package g2001_2100.s2034_stock_price_fluctuation;
2+
3+
// #Medium #Hash_Table #Design #Heap_Priority_Queue #Ordered_Set #Data_Stream
4+
// #2022_05_25_Time_163_ms_(65.51%)_Space_155.8_MB_(37.90%)
5+
6+
import java.util.HashMap;
7+
import java.util.Map;
8+
import java.util.PriorityQueue;
9+
10+
public class StockPrice {
11+
private static class Record {
12+
Integer time;
13+
Integer price;
14+
15+
Record(Integer time, Integer price) {
16+
this.time = time;
17+
this.price = price;
18+
}
19+
}
20+
21+
Map<Integer, Integer> map;
22+
PriorityQueue<Record> maxHeap;
23+
PriorityQueue<Record> minHeap;
24+
Integer latestTimestamp = 0;
25+
26+
public StockPrice() {
27+
map = new HashMap<>();
28+
maxHeap =
29+
new PriorityQueue<>(
30+
(r1, r2) -> {
31+
if (r1.price.equals(r2.price)) {
32+
return 0;
33+
} else {
34+
return r1.price > r2.price ? -1 : 1;
35+
}
36+
});
37+
minHeap =
38+
new PriorityQueue<>(
39+
(r1, r2) -> {
40+
if (r1.price.equals(r2.price)) {
41+
return 0;
42+
} else {
43+
return r1.price < r2.price ? -1 : 1;
44+
}
45+
});
46+
}
47+
48+
public void update(int timestamp, int price) {
49+
latestTimestamp = Math.max(timestamp, latestTimestamp);
50+
maxHeap.offer(new Record(timestamp, price));
51+
minHeap.offer(new Record(timestamp, price));
52+
map.put(timestamp, price);
53+
}
54+
55+
public int current() {
56+
return map.get(latestTimestamp);
57+
}
58+
59+
public int maximum() {
60+
while (true) {
61+
Record r = maxHeap.peek();
62+
if (map.get(r.time).equals(r.price)) {
63+
return r.price;
64+
}
65+
maxHeap.poll();
66+
}
67+
}
68+
69+
public int minimum() {
70+
while (true) {
71+
Record r = minHeap.peek();
72+
if (map.get(r.time).equals(r.price)) {
73+
return r.price;
74+
}
75+
minHeap.poll();
76+
}
77+
}
78+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
2034\. Stock Price Fluctuation
2+
3+
Medium
4+
5+
You are given a stream of **records** about a particular stock. Each record contains a **timestamp** and the corresponding **price** of the stock at that timestamp.
6+
7+
Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream **correcting** the price of the previous wrong record.
8+
9+
Design an algorithm that:
10+
11+
* **Updates** the price of the stock at a particular timestamp, **correcting** the price from any previous records at the timestamp.
12+
* Finds the **latest price** of the stock based on the current records. The **latest price** is the price at the latest timestamp recorded.
13+
* Finds the **maximum price** the stock has been based on the current records.
14+
* Finds the **minimum price** the stock has been based on the current records.
15+
16+
Implement the `StockPrice` class:
17+
18+
* `StockPrice()` Initializes the object with no price records.
19+
* `void update(int timestamp, int price)` Updates the `price` of the stock at the given `timestamp`.
20+
* `int current()` Returns the **latest price** of the stock.
21+
* `int maximum()` Returns the **maximum price** of the stock.
22+
* `int minimum()` Returns the **minimum price** of the stock.
23+
24+
**Example 1:**
25+
26+
**Input** ["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"] [[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]
27+
28+
**Output:** [null, null, null, 5, 10, null, 5, null, 2]
29+
30+
**Explanation:**
31+
32+
StockPrice stockPrice = new StockPrice();
33+
34+
stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].
35+
36+
stockPrice.update(2, 5); // Timestamps are [1,2] with corresponding prices [10,5].
37+
38+
stockPrice.current(); // return 5, the latest timestamp is 2 with the price being 5.
39+
40+
stockPrice.maximum(); // return 10, the maximum price is 10 at timestamp 1.
41+
42+
stockPrice.update(1, 3); // The previous timestamp 1 had the wrong price, so it is updated to 3. // Timestamps are [1,2] with corresponding prices [3,5].
43+
44+
stockPrice.maximum(); // return 5, the maximum price is 5 after the correction.
45+
46+
stockPrice.update(4, 2); // Timestamps are [1,2,4] with corresponding prices [3,5,2].
47+
48+
stockPrice.minimum(); // return 2, the minimum price is 2 at timestamp 4.
49+
50+
**Constraints:**
51+
52+
* <code>1 <= timestamp, price <= 10<sup>9</sup></code>
53+
* At most <code>10<sup>5</sup></code> calls will be made **in total** to `update`, `current`, `maximum`, and `minimum`.
54+
* `current`, `maximum`, and `minimum` will be called **only after** `update` has been called **at least once**.
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package g2001_2100.s2035_partition_array_into_two_arrays_to_minimize_sum_difference;
2+
3+
// #Hard #Array #Dynamic_Programming #Binary_Search #Two_Pointers #Bit_Manipulation #Ordered_Set
4+
// #Bitmask #2022_05_25_Time_1336_ms_(39.36%)_Space_117.6_MB_(50.53%)
5+
6+
import java.util.ArrayList;
7+
import java.util.Collections;
8+
import java.util.List;
9+
10+
public class Solution {
11+
public int minimumDifference(int[] nums) {
12+
if (nums == null || nums.length == 0) {
13+
return -1;
14+
}
15+
int n = nums.length / 2;
16+
int sum = 0;
17+
List<List<Integer>> arr1 = new ArrayList<>();
18+
List<List<Integer>> arr2 = new ArrayList<>();
19+
for (int i = 0; i <= n; i++) {
20+
arr1.add(new ArrayList<>());
21+
arr2.add(new ArrayList<>());
22+
if (i < n) {
23+
sum += nums[i];
24+
sum += nums[i + n];
25+
}
26+
}
27+
for (int state = 0; state < (1 << n); state++) {
28+
int sum1 = 0;
29+
int sum2 = 0;
30+
for (int i = 0; i < n; i++) {
31+
if ((state & (1 << i)) == 0) {
32+
continue;
33+
}
34+
int a1 = nums[i];
35+
int a2 = nums[i + n];
36+
sum1 += a1;
37+
sum2 += a2;
38+
}
39+
int numOfEleInSet = Integer.bitCount(state);
40+
arr1.get(numOfEleInSet).add(sum1);
41+
arr2.get(numOfEleInSet).add(sum2);
42+
}
43+
for (int i = 0; i <= n; i++) {
44+
Collections.sort(arr2.get(i));
45+
}
46+
int min = Integer.MAX_VALUE;
47+
for (int i = 0; i <= n; i++) {
48+
List<Integer> sums1 = arr1.get(i);
49+
List<Integer> sums2 = arr2.get(n - i);
50+
for (int s1 : sums1) {
51+
int idx = Collections.binarySearch(sums2, sum / 2 - s1);
52+
if (idx < 0) {
53+
idx = -(idx + 1);
54+
}
55+
if (idx < sums1.size()) {
56+
min =
57+
Math.min(
58+
min,
59+
Math.abs((sum - s1 - sums2.get(idx)) - (sums2.get(idx) + s1)));
60+
}
61+
if (idx - 1 >= 0) {
62+
min =
63+
Math.min(
64+
min,
65+
Math.abs(
66+
(sum - s1 - sums2.get(idx - 1))
67+
- (sums2.get(idx - 1) + s1)));
68+
}
69+
}
70+
}
71+
return min;
72+
}
73+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2035\. Partition Array Into Two Arrays to Minimize Sum Difference
2+
3+
Hard
4+
5+
You are given an integer array `nums` of `2 * n` integers. You need to partition `nums` into **two** arrays of length `n` to **minimize the absolute difference** of the **sums** of the arrays. To partition `nums`, put each element of `nums` into **one** of the two arrays.
6+
7+
Return _the **minimum** possible absolute difference_.
8+
9+
**Example 1:**
10+
11+
![example-1](https://assets.leetcode.com/uploads/2021/10/02/ex1.png)
12+
13+
**Input:** nums = [3,9,7,3]
14+
15+
**Output:** 2
16+
17+
**Explanation:** One optimal partition is: [3,9] and [7,3]. The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
18+
19+
**Example 2:**
20+
21+
**Input:** nums = [-36,36]
22+
23+
**Output:** 72
24+
25+
**Explanation:** One optimal partition is: [-36] and [36]. The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
26+
27+
**Example 3:**
28+
29+
![example-3](https://assets.leetcode.com/uploads/2021/10/02/ex3.png)
30+
31+
**Input:** nums = [2,-1,0,4,-2,-9]
32+
33+
**Output:** 0
34+
35+
**Explanation:** One optimal partition is: [2,4,-9] and [-1,0,-2]. The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
36+
37+
**Constraints:**
38+
39+
* `1 <= n <= 15`
40+
* `nums.length == 2 * n`
41+
* <code>-10<sup>7</sup> <= nums[i] <= 10<sup>7</sup></code>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package g2001_2100.s2037_minimum_number_of_moves_to_seat_everyone;
2+
3+
// #Easy #Array #Sorting #2022_05_25_Time_5_ms_(22.01%)_Space_43.7_MB_(67.19%)
4+
5+
import java.util.Arrays;
6+
7+
public class Solution {
8+
public int minMovesToSeat(int[] seats, int[] students) {
9+
int ans = 0;
10+
Arrays.sort(seats);
11+
Arrays.sort(students);
12+
for (int i = 0; i < seats.length; i++) {
13+
ans += Math.abs(seats[i] - students[i]);
14+
}
15+
return ans;
16+
}
17+
}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
2037\. Minimum Number of Moves to Seat Everyone
2+
3+
Easy
4+
5+
There are `n` seats and `n` students in a room. You are given an array `seats` of length `n`, where `seats[i]` is the position of the <code>i<sup>th</sup></code> seat. You are also given the array `students` of length `n`, where `students[j]` is the position of the <code>j<sup>th</sup></code> student.
6+
7+
You may perform the following move any number of times:
8+
9+
* Increase or decrease the position of the <code>i<sup>th</sup></code> student by `1` (i.e., moving the <code>i<sup>th</sup></code> student from position `x` to `x + 1` or `x - 1`)
10+
11+
Return _the **minimum number of moves** required to move each student to a seat_ _such that no two students are in the same seat._
12+
13+
Note that there may be **multiple** seats or students in the **same** position at the beginning.
14+
15+
**Example 1:**
16+
17+
**Input:** seats = [3,1,5], students = [2,7,4]
18+
19+
**Output:** 4
20+
21+
**Explanation:**
22+
23+
The students are moved as follows:
24+
25+
- The first student is moved from from position 2 to position 1 using 1 move.
26+
27+
- The second student is moved from from position 7 to position 5 using 2 moves.
28+
29+
- The third student is moved from from position 4 to position 3 using 1 move.
30+
31+
In total, 1 + 2 + 1 = 4 moves were used.
32+
33+
**Example 2:**
34+
35+
**Input:** seats = [4,1,5,9], students = [1,3,2,6]
36+
37+
**Output:** 7
38+
39+
**Explanation:**
40+
41+
The students are moved as follows:
42+
43+
- The first student is not moved.
44+
45+
- The second student is moved from from position 3 to position 4 using 1 move.
46+
47+
- The third student is moved from from position 2 to position 5 using 3 moves.
48+
49+
- The fourth student is moved from from position 6 to position 9 using 3 moves.
50+
51+
In total, 0 + 1 + 3 + 3 = 7 moves were used.
52+
53+
**Example 3:**
54+
55+
**Input:** seats = [2,2,6,6], students = [1,3,2,6]
56+
57+
**Output:** 4
58+
59+
**Explanation:** Note that there are two seats at position 2 and two seats at position 6.
60+
61+
The students are moved as follows:
62+
63+
- The first student is moved from from position 1 to position 2 using 1 move.
64+
65+
- The second student is moved from from position 3 to position 6 using 3 moves.
66+
67+
- The third student is not moved.
68+
69+
- The fourth student is not moved.
70+
71+
In total, 1 + 3 + 0 + 0 = 4 moves were used.
72+
73+
**Constraints:**
74+
75+
* `n == seats.length == students.length`
76+
* `1 <= n <= 100`
77+
* `1 <= seats[i], students[j] <= 100`
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package g2001_2100.s2034_stock_price_fluctuation;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class StockPriceTest {
9+
@Test
10+
void stockPriceTest() {
11+
StockPrice stockPrice = new StockPrice();
12+
stockPrice.update(1, 10);
13+
stockPrice.update(2, 5);
14+
assertThat(stockPrice.current(), equalTo(5));
15+
assertThat(stockPrice.maximum(), equalTo(10));
16+
stockPrice.update(1, 3);
17+
assertThat(stockPrice.maximum(), equalTo(5));
18+
stockPrice.update(4, 2);
19+
assertThat(stockPrice.minimum(), equalTo(2));
20+
}
21+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g2001_2100.s2035_partition_array_into_two_arrays_to_minimize_sum_difference;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void minimumDifference() {
11+
assertThat(new Solution().minimumDifference(new int[] {3, 9, 7, 3}), equalTo(2));
12+
}
13+
14+
@Test
15+
void minimumDifference2() {
16+
assertThat(new Solution().minimumDifference(new int[] {-36, 36}), equalTo(72));
17+
}
18+
19+
@Test
20+
void minimumDifference3() {
21+
assertThat(new Solution().minimumDifference(new int[] {2, -1, 0, 4, -2, -9}), equalTo(0));
22+
}
23+
}

0 commit comments

Comments
 (0)