Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package g1401_1500.s1471_the_k_strongest_values_in_an_array;

// #Medium #Array #Sorting #Two_Pointers #2022_03_29_Time_37_ms_(88.20%)_Space_81.7_MB_(70.81%)

import java.util.Arrays;

public class Solution {
public int[] getStrongest(int[] arr, int k) {
Arrays.sort(arr);
int[] array = new int[k];
int median = arr[(arr.length - 1) / 2];
int start = 0;
int end = arr.length - 1;
for (int i = 0; i < k; i++) {
if (Math.abs(arr[end] - median) >= Math.abs(arr[start] - median)) {
array[i] = arr[end];
end -= 1;
} else {
array[i] = arr[start];
start += 1;
}
}
return array;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
1471\. The k Strongest Values in an Array

Medium

Given an array of integers `arr` and an integer `k`.

A value `arr[i]` is said to be stronger than a value `arr[j]` if `|arr[i] - m| > |arr[j] - m|` where `m` is the **median** of the array.
If `|arr[i] - m| == |arr[j] - m|`, then `arr[i]` is said to be stronger than `arr[j]` if `arr[i] > arr[j]`.

Return _a list of the strongest `k`_ values in the array. return the answer **in any arbitrary order**.

**Median** is the middle value in an ordered integer list. More formally, if the length of the list is n, the median is the element in position `((n - 1) / 2)` in the sorted list **(0-indexed)**.

* For `arr = [6, -3, 7, 2, 11]`, `n = 5` and the median is obtained by sorting the array `arr = [-3, 2, 6, 7, 11]` and the median is `arr[m]` where `m = ((5 - 1) / 2) = 2`. The median is `6`.
* For `arr = [-7, 22, 17, 3]`, `n = 4` and the median is obtained by sorting the array `arr = [-7, 3, 17, 22]` and the median is `arr[m]` where `m = ((4 - 1) / 2) = 1`. The median is `3`.

**Example 1:**

**Input:** arr = [1,2,3,4,5], k = 2

**Output:** [5,1]

**Explanation:** Median is 3, the elements of the array sorted by the strongest are [5,1,4,2,3]. The strongest 2 elements are [5, 1]. [1, 5] is also **accepted** answer. Please note that although |5 - 3| == |1 - 3| but 5 is stronger than 1 because 5 > 1.

**Example 2:**

**Input:** arr = [1,1,3,5,5], k = 2

**Output:** [5,5]

**Explanation:** Median is 3, the elements of the array sorted by the strongest are [5,5,1,1,3]. The strongest 2 elements are [5, 5].

**Example 3:**

**Input:** arr = [6,7,11,7,6,8], k = 5

**Output:** [11,8,6,6,7]

**Explanation:** Median is 7, the elements of the array sorted by the strongest are [11,8,6,6,7,7]. Any permutation of [11,8,6,6,7] is **accepted**.

**Constraints:**

* <code>1 <= arr.length <= 10<sup>5</sup></code>
* <code>-10<sup>5</sup> <= arr[i] <= 10<sup>5</sup></code>
* `1 <= k <= arr.length`
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package g1401_1500.s1472_design_browser_history;

// #Medium #Array #Stack #Design #Linked_List #Data_Stream #Doubly_Linked_List
// #2022_03_29_Time_76_ms_(82.33%)_Space_86.4_MB_(14.42%)

public class BrowserHistory {

static class Node {
Node prev;
Node next;
String url;

Node(String url) {
this.url = url;
this.prev = null;
this.next = null;
}
}

private Node curr;

public BrowserHistory(String homepage) {
curr = new Node(homepage);
}

public void visit(String url) {
Node newNode = new Node(url);
curr.next = newNode;
newNode.prev = curr;
curr = curr.next;
}

public String back(int steps) {
while (curr.prev != null && steps-- > 0) {
curr = curr.prev;
}
return curr.url;
}

public String forward(int steps) {
while (curr.next != null && steps-- > 0) {
curr = curr.next;
}
return curr.url;
}
}
50 changes: 50 additions & 0 deletions src/main/java/g1401_1500/s1472_design_browser_history/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
1472\. Design Browser History

Medium

You have a **browser** of one tab where you start on the `homepage` and you can visit another `url`, get back in the history number of `steps` or move forward in the history number of `steps`.

Implement the `BrowserHistory` class:

* `BrowserHistory(string homepage)` Initializes the object with the `homepage` of the browser.
* `void visit(string url)` Visits `url` from the current page. It clears up all the forward history.
* `string back(int steps)` Move `steps` back in history. If you can only return `x` steps in the history and `steps > x`, you will return only `x` steps. Return the current `url` after moving back in history **at most** `steps`.
* `string forward(int steps)` Move `steps` forward in history. If you can only forward `x` steps in the history and `steps > x`, you will forward only `x` steps. Return the current `url` after forwarding in history **at most** `steps`.

**Example:**

**Input:** ["BrowserHistory","visit","visit","visit","back","back","forward","visit","forward","back","back"] [["leetcode.com"],["google.com"],["facebook.com"],["youtube.com"],[1],[1],[1],["linkedin.com"],[2],[2],[7]]

**Output:** [null,null,null,null,"facebook.com","google.com","facebook.com",null,"linkedin.com","google.com","leetcode.com"]

**Explanation:**

BrowserHistory browserHistory = new BrowserHistory("leetcode.com");

browserHistory.visit("google.com"); // You are in "leetcode.com". Visit "google.com"

browserHistory.visit("facebook.com"); // You are in "google.com". Visit "facebook.com"

browserHistory.visit("youtube.com"); // You are in "facebook.com". Visit "youtube.com"

browserHistory.back(1); // You are in "youtube.com", move back to "facebook.com" return "facebook.com"

browserHistory.back(1); // You are in "facebook.com", move back to "google.com" return "google.com"

browserHistory.forward(1); // You are in "google.com", move forward to "facebook.com" return "facebook.com"

browserHistory.visit("linkedin.com"); // You are in "facebook.com". Visit "linkedin.com"

browserHistory.forward(2); // You are in "linkedin.com", you cannot move forward any steps.

browserHistory.back(2); // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"

browserHistory.back(7); // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"

**Constraints:**

* `1 <= homepage.length <= 20`
* `1 <= url.length <= 20`
* `1 <= steps <= 100`
* `homepage` and `url` consist of '.' or lower case English letters.
* At most `5000` calls will be made to `visit`, `back`, and `forward`.
50 changes: 50 additions & 0 deletions src/main/java/g1401_1500/s1473_paint_house_iii/Solution.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package g1401_1500.s1473_paint_house_iii;

// #Hard #Array #Dynamic_Programming #2022_03_29_Time_26_ms_(89.13%)_Space_42.9_MB_(91.75%)

public class Solution {
private int[][][] memo;
private int[] houses;
private int nColors;
private int[][] cost;

public int minCost(int[] houses, int[][] cost, int nColors, int tGroups) {
this.cost = cost;
this.houses = houses;
this.memo = new int[houses.length][nColors + 1][tGroups + 1];
this.nColors = nColors;

int dp = dp(0, 0, tGroups);
return dp == Integer.MAX_VALUE ? -1 : dp;
}

private int dp(int ithEl, int prevClr, int tGroups) {
if (ithEl == houses.length) {
return tGroups == 0 ? 0 : Integer.MAX_VALUE;
}
if (ithEl < houses.length && tGroups < 0) {
return Integer.MAX_VALUE;
}
if (memo[ithEl][prevClr][tGroups] == 0) {
int currC = houses[ithEl];
int res = Integer.MAX_VALUE;
if (currC != 0) {
int grpLeft = currC == prevClr ? tGroups : tGroups - 1;
res = dp(ithEl + 1, currC, grpLeft);
} else {
for (int clr = 1; clr <= nColors; clr++) {
int grpLeft = clr == prevClr ? tGroups : tGroups - 1;
int dp = dp(ithEl + 1, clr, grpLeft);
res =
Math.min(
res,
dp != Integer.MAX_VALUE
? cost[ithEl][clr - 1] + dp
: Integer.MAX_VALUE);
}
}
memo[ithEl][prevClr][tGroups] = res;
}
return memo[ithEl][prevClr][tGroups];
}
}
58 changes: 58 additions & 0 deletions src/main/java/g1401_1500/s1473_paint_house_iii/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
1473\. Paint House III

Hard

There is a row of `m` houses in a small city, each house must be painted with one of the `n` colors (labeled from `1` to `n`), some houses that have been painted last summer should not be painted again.

A neighborhood is a maximal group of continuous houses that are painted with the same color.

* For example: `houses = [1,2,2,3,3,2,1,1]` contains `5` neighborhoods `[{1}, {2,2}, {3,3}, {2}, {1,1}]`.

Given an array `houses`, an `m x n` matrix `cost` and an integer `target` where:

* `houses[i]`: is the color of the house `i`, and `0` if the house is not painted yet.
* `cost[i][j]`: is the cost of paint the house `i` with the color `j + 1`.

Return _the minimum cost of painting all the remaining houses in such a way that there are exactly_ `target` _neighborhoods_. If it is not possible, return `-1`.

**Example 1:**

**Input:** houses = [0,0,0,0,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3

**Output:** 9

**Explanation:** Paint houses of this way [1,2,2,1,1]

This array contains target = 3 neighborhoods, [{1}, {2,2}, {1,1}].

Cost of paint all houses (1 + 1 + 1 + 1 + 5) = 9.

**Example 2:**

**Input:** houses = [0,2,1,2,0], cost = [[1,10],[10,1],[10,1],[1,10],[5,1]], m = 5, n = 2, target = 3

**Output:** 11

**Explanation:** Some houses are already painted, Paint the houses of this way [2,2,1,2,2]

This array contains target = 3 neighborhoods, [{2,2}, {1}, {2,2}].

Cost of paint the first and last house (10 + 1) = 11.

**Example 3:**

**Input:** houses = [3,1,2,3], cost = [[1,1,1],[1,1,1],[1,1,1],[1,1,1]], m = 4, n = 3, target = 3

**Output:** -1

**Explanation:** Houses are already painted with a total of 4 neighborhoods [{3},{1},{2},{3}] different of target = 3.

**Constraints:**

* `m == houses.length == cost.length`
* `n == cost[i].length`
* `1 <= m <= 100`
* `1 <= n <= 20`
* `1 <= target <= m`
* `0 <= houses[i] <= n`
* <code>1 <= cost[i][j] <= 10<sup>4</sup></code>
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package g1401_1500.s1471_the_k_strongest_values_in_an_array;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class SolutionTest {
@Test
void getStrongest() {
assertThat(
new Solution().getStrongest(new int[] {1, 2, 3, 4, 5}, 2),
equalTo(new int[] {5, 1}));
}

@Test
void getStrongest2() {
assertThat(
new Solution().getStrongest(new int[] {1, 1, 3, 5, 5}, 2),
equalTo(new int[] {5, 5}));
}

@Test
void getStrongest3() {
assertThat(
new Solution().getStrongest(new int[] {6, 7, 11, 7, 6, 8}, 5),
equalTo(new int[] {11, 8, 6, 6, 7}));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package g1401_1500.s1472_design_browser_history;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class BrowserHistoryTest {
@Test
void browserHistoryTest() {
BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com");
browserHistory.visit("facebook.com");
browserHistory.visit("youtube.com");
assertThat(browserHistory.back(1), equalTo("facebook.com"));
assertThat(browserHistory.back(1), equalTo("google.com"));
assertThat(browserHistory.forward(1), equalTo("facebook.com"));
browserHistory.visit("linkedin.com");
assertThat(browserHistory.forward(2), equalTo("linkedin.com"));
assertThat(browserHistory.back(2), equalTo("google.com"));
assertThat(browserHistory.back(7), equalTo("leetcode.com"));
}
}
44 changes: 44 additions & 0 deletions src/test/java/g1401_1500/s1473_paint_house_iii/SolutionTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package g1401_1500.s1473_paint_house_iii;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;

class SolutionTest {
@Test
void minCost() {
assertThat(
new Solution()
.minCost(
new int[] {0, 0, 0, 0, 0},
new int[][] {{1, 10}, {10, 1}, {10, 1}, {1, 10}, {5, 1}},
2,
3),
equalTo(9));
}

@Test
void minCost2() {
assertThat(
new Solution()
.minCost(
new int[] {0, 2, 1, 2, 0},
new int[][] {{1, 10}, {10, 1}, {10, 1}, {1, 10}, {5, 1}},
2,
3),
equalTo(11));
}

@Test
void minCost3() {
assertThat(
new Solution()
.minCost(
new int[] {3, 1, 2, 3},
new int[][] {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {1, 1, 1}},
3,
3),
equalTo(-1));
}
}