Tuesday, September 29, 2020

LeetCode [871] Minimum Number of Refueling Stops

 871. Minimum Number of Refueling Stops

Hard

A car travels from a starting position to a destination which is target miles east of the starting position.

Along the way, there are gas stations.  Each station[i] represents a gas station that is station[i][0] miles east of the starting position, and has station[i][1] liters of gas.

The car starts with an infinite tank of gas, which initially has startFuel liters of fuel in it.  It uses 1 liter of gas per 1 mile that it drives.

When the car reaches a gas station, it may stop and refuel, transferring all the gas from the station into the car.

What is the least number of refueling stops the car must make in order to reach its destination?  If it cannot reach the destination, return -1.

Note that if the car reaches a gas station with 0 fuel left, the car can still refuel there.  If the car reaches the destination with 0 fuel left, it is still considered to have arrived.

 

Example 1:

Input: target = 1, startFuel = 1, stations = []
Output: 0
Explanation: We can reach the target without refueling.

Example 2:

Input: target = 100, startFuel = 1, stations = [[10,100]]
Output: -1
Explanation: We can't reach the target (or even the first gas station).

Example 3:

Input: target = 100, startFuel = 10, stations = [[10,60],[20,30],[30,30],[60,40]]
Output: 2
Explanation: 
We start with 10 liters of fuel.
We drive to position 10, expending 10 liters of fuel.  We refuel from 0 liters to 60 liters of gas.
Then, we drive from position 10 to position 60 (expending 50 liters of fuel),
and refuel from 10 liters to 50 liters of gas.  We then drive to and reach the target.
We made 2 refueling stops along the way, so we return 2.

 

Note:

  1. 1 <= target, startFuel, stations[i][1] <= 10^9
  2. 0 <= stations.length <= 500
  3. 0 < stations[0][0] < stations[1][0] < ... < stations[stations.length-1][0] < target
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public int minRefuelStops(int target, int startFuel, int[][] stations) {
        int n = stations.length;
        long[] dp = new long[n+1];//dp[i] is the furthest we can get with t refueling
        dp[0] = startFuel;

        for(int i=0; i<n; ++i){
            int location = stations[i][0];
            int fuel = stations[i][1];
            int maxRefuelings = i+1;
            //update dp with stations[i]
            //because the maxRefueling we can get at stations[i] is i+1
            //we only need to update dp[0..i]
            for(int t=i; t>=0; --t){
                if(dp[t]<location) break;//dp[t] cannot reach location
                dp[t+1] = Math.max(dp[t+1], dp[t]+fuel);
            }
        }

        for(int i=0; i<=n; ++i){
            if(dp[i]>=target) return i;
        }
        return -1;
    }
}

LeetCode [1499] Max Value of Equation

 1499. Max Value of Equation

Hard

Given an array points containing the coordinates of points on a 2D plane, sorted by the x-values, where points[i] = [xi, yi] such that xi < xj for all 1 <= i < j <= points.length. You are also given an integer k.

Find the maximum value of the equation yi + yj + |xi - xj| where |xi - xj| <= k and 1 <= i < j <= points.length. It is guaranteed that there exists at least one pair of points that satisfy the constraint |xi - xj| <= k.

 

Example 1:

Input: points = [[1,3],[2,0],[5,10],[6,-10]], k = 1
Output: 4
Explanation: The first two points satisfy the condition |xi - xj| <= 1 and if we calculate the equation we get 3 + 0 + |1 - 2| = 4. Third and fourth points also satisfy the condition and give a value of 10 + -10 + |5 - 6| = 1.
No other pairs satisfy the condition, so we return the max of 4 and 1.

Example 2:

Input: points = [[0,0],[3,0],[9,2]], k = 3
Output: 3
Explanation: Only the first two points have an absolute difference of 3 or less in the x-values, and give the value of 0 + 0 + |0 - 3| = 3.

 

Constraints:

  • 2 <= points.length <= 10^5
  • points[i].length == 2
  • -10^8 <= points[i][0], points[i][1] <= 10^8
  • 0 <= k <= 2 * 10^8
  • points[i][0] < points[j][0] for all 1 <= i < j <= points.length
  • xi form a strictly increasing sequence.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public int findMaxValueOfEquation(int[][] points, int k) {
        int maxR = Integer.MIN_VALUE;
        //<yi-xi, xi>
        PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> {
                if(a[0]==b[0]) return a[1]-b[1];
                else return b[0]-a[0];
            }
        );
        for(int i=0; i<points.length; ++i){
            while(!pq.isEmpty() && points[i][0]-pq.peek()[1]>k){
                pq.poll();
            }
            if(!pq.isEmpty()){
                int r = points[i][0]+points[i][1]+pq.peek()[0];
                maxR = Math.max(r, maxR);
            }
            pq.add(new int[]{points[i][1]-points[i][0], points[i][0]});
        }
        return maxR;
    }
}

LeetCode [830] Positions of Large Groups

 830. Positions of Large Groups

Easy

In a string s of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like s = "abbxxxxzyy" has the groups "a""bb""xxxx""z", and "yy".

A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6].

A group is considered large if it has 3 or more characters.

Return the intervals of every large group sorted in increasing order by start index.

 

Example 1:

Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.

Example 2:

Input: s = "abc"
Output: []
Explanation: We have groups "a", "b", and "c", none of which are large groups.

Example 3:

Input: s = "abcdddeeeeaabbbcd"
Output: [[3,5],[6,9],[12,14]]
Explanation: The large groups are "ddd", "eeee", and "bbb".

Example 4:

Input: s = "aba"
Output: []

 

Constraints:

  • 1 <= s.length <= 1000
  • s contains lower-case English letters only.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public List<List<Integer>> largeGroupPositions(String s) {
        List<List<Integer>> ret = new ArrayList<>();
        int n = s.length(), i=0, j=0;
        while(j<n){
            while(j<n && s.charAt(i)==s.charAt(j)){
                j++;
            }
            if(j-i>=3){
                ret.add(Arrays.asList(new Integer[] {i, j-1}));
            }
            i=j;
        }
        return ret;
    }
}

Monday, September 28, 2020

LeetCode [1218] Longest Arithmetic Subsequence of Given Difference

 1218. Longest Arithmetic Subsequence of Given Difference

Medium

Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.

 

Example 1:

Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].

Example 2:

Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.

Example 3:

Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].

 

Constraints:

  • 1 <= arr.length <= 10^5
  • -10^4 <= arr[i], difference <= 10^4
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public int longestSubsequence(int[] arr, int difference) {
        int n = arr.length, maxLen = 0;;
        Map<Integer, Integer> map = new HashMap<>();//longest len, last ele
        for(int i=0; i<n; ++i){
            int l = map.getOrDefault(arr[i]-difference, 0) + 1;
            maxLen = Math.max(maxLen, l);
            map.put(arr[i], l);
        }
        return maxLen;
    }
}

LeetCode [1138] Alphabet Board Path

 1138. Alphabet Board Path

Medium

On an alphabet board, we start at position (0, 0), corresponding to character board[0][0].

Here, board = ["abcde", "fghij", "klmno", "pqrst", "uvwxy", "z"], as shown in the diagram below.

We may make the following moves:

  • 'U' moves our position up one row, if the position exists on the board;
  • 'D' moves our position down one row, if the position exists on the board;
  • 'L' moves our position left one column, if the position exists on the board;
  • 'R' moves our position right one column, if the position exists on the board;
  • '!' adds the character board[r][c] at our current position (r, c) to the answer.

(Here, the only positions that exist on the board are positions with letters on them.)

Return a sequence of moves that makes our answer equal to target in the minimum number of moves.  You may return any path that does so.

 

Example 1:

Input: target = "leet"
Output: "DDR!UURRR!!DDD!"

Example 2:

Input: target = "code"
Output: "RR!DDRR!UUL!R!"

 

Constraints:

  • 1 <= target.length <= 100
  • target consists only of English lowercase letters.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
    public String alphabetBoardPath(String target) {
        int i=0, j=0, pos=0, n = target.length();
        String path="";
        while(pos<n){
            int ch = i*5+j+'a';//char at [i,j]
            while(pos<n && ch==target.charAt(pos)){
                path += "!";
                pos++;
            }
    
            if(pos==n){
                return path;
            }
    
            int nexChar = target.charAt(pos)-'a';
            int nextRow = nexChar/5, nextCol = nexChar%5;
            char d;
            if(nextRow<i){
                i--;
                d = 'U';
            }else if(nextCol<j){
                j--;
                d = 'L';
            }else if(nextRow>i){
                i++;
                d = 'D';
            }else{
                j++;
                d = 'R';
            }
            path+=d;
        }

        return "";
    }
}

LeetCode [688] Knight Probability in Chessboard

 688. Knight Probability in Chessboard

Medium

On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).

A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.

 

 

Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there.

The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.

 

Example:

Input: 3, 2, 0, 0
Output: 0.0625
Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
From each of those positions, there are also two moves that will keep the knight on the board.
The total probability the knight stays on the board is 0.0625.

 

Note:

  • N will be between 1 and 25.
  • K will be between 0 and 100.
  • The knight always initially starts on the board.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
    private int[][]dir = new int[][]{{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};
    private double[][][] dp;
    public double knightProbability(int N, int K, int r, int c) {
        dp = new double[N][N][K + 1];
        return find(N,K,r,c);
    }
    public double find(int N,int K,int r,int c){
        if(r < 0 || r > N - 1 || c < 0 || c > N - 1) return 0;
        if(K == 0)  return 1;
        if(dp[r][c][K] != 0) return dp[r][c][K];
        double rate = 0;
        for(int i = 0;i < dir.length;i++)   rate += 0.125 * find(N,K - 1,r + dir[i][0],c + dir[i][1]);
        dp[r][c][K] = rate;
        return rate;
    }
}