[algorithm] the 191st weekly race of LeetCode 20200531(Java)

Week 191

20200531

1464. Maximum product of two elements in an array

Title Description 1

To give you an integer array nums, please select two different subscripts I and j of the array to maximize (nums[i]-1)*(nums[j]-1).

Please calculate and return the maximum value of the formula.

Example 1:

Input: nums = [3,4,5,2]
Output: 12
 Explanation: if the subscripts i=1 and j=2 are selected (the subscripts start from 0), the maximum value can be obtained, (nums [1] - 1 * (nums [2] - 1) = (4-1) * (5-1) = 3 * 4 = 12.

Example 2:

Input: nums = [1,5,4,5]
Output: 16
 Explanation: select the subscripts i=1 and j=3 (subscripts start from 0) to get the maximum value (5-1) * (5-1) = 16.

Example 3:

Input: nums = [3,7]
Output: 12

Tips:

  • 2 <= nums.length <= 500
  • 1 <= nums[i] <= 10^3

Answer 1

Bubble mode, but sorting two is OK.

class Solution {
    public int maxProduct(int[] nums) {
        int res = 0;
        int temp = 0;
        int len = nums.length;
        for(int i = 0; i < 2; i++){
            for(int j = 0; j < nums.length - i - 1; j++){
                if(nums[j] >= nums[j + 1]){
                    temp = nums[j];
                    nums[j] = nums[j + 1];
                    nums[j + 1] = temp;
                }
            }
        }
        return (nums[len - 1] - 1) * (nums[len - 2] - 1);

    }
}

1465. Cake with the largest area after cutting

Title Description 2

The height of the rectangular cake is h and the width is w. here are two integer arrays, horizontalCuts and verticalCuts, where horizontalCuts[i] is the distance from the top of the rectangular cake to the i-th horizontal cut, similarly, verticalCuts[j] is the distance from the left side of the rectangular cake to the j-th vertical cut.

After you cut according to the horizontal and vertical positions provided in the array horizontal cuts and vertical cuts, please find the cake with the largest area and return its area. Because the answer may be a large number, you need to leave the result 10 ^ 9 + 7 and return it.

Example 1:

Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4
 Explanation: in the matrix cake shown above, the red line represents the cut in the horizontal and vertical directions. After cutting the cake, the green one has the largest area.

Example 2:

Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
Output: 6
 Explanation: in the matrix cake shown above, the red line represents the cut in the horizontal and vertical directions. After the cake is cut, the green and yellow cakes have the largest area.

Example 3:

Input: h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
Output: 9

Tips:

  • 2 <= h, w <= 10^9
  • 1 <= horizontalCuts.length < min(h, 10^5)
  • 1 <= verticalCuts.length < min(w, 10^5)
  • 1 <= horizontalCuts[i] < h
  • 1 <= verticalCuts[i] < w
  • Topic data ensures that all elements in horizontalCuts are different
  • Topic data ensures that all elements in verticalCuts are different

Answer 2

Find the maximum distance of row and col respectively, and multiply the two distances.
tips: the results are all represented by long, and the last one is redundant for 100000007, and then the output is transferred to int.

class Solution {
    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
        int hmax = 0, wmax = 0;
        Arrays.sort(horizontalCuts);
        Arrays.sort(verticalCuts);
        for(int i = 0; i < horizontalCuts.length - 1; i++){
            hmax = Math.max(hmax, horizontalCuts[i + 1] - horizontalCuts[i]);
        }
        hmax = Math.max(hmax, horizontalCuts[0] - 0);
        hmax = Math.max(hmax, h - horizontalCuts[horizontalCuts.length - 1]);
        for(int i = 0; i < verticalCuts.length - 1; i++){
            wmax = Math.max(wmax, verticalCuts[i + 1] - verticalCuts[i]);
        }
        wmax = Math.max(wmax, verticalCuts[0] - 0);
        wmax = Math.max(wmax, w - verticalCuts[verticalCuts.length - 1]);
        long ans = (long)hmax * (long)wmax;
        long a = 1000000007;
        return (int)(ans%a);

    }
}

1466. Reroute

Title Description 3

N cities, numbered from 0 to n-1, with n-1 routes in total. Therefore, there is only one route to travel between two different cities (the network of routes forms a tree). Last year, the Ministry of transport decided to reroute to change congestion.

Routes are represented by connections, where connections[i] = [a, b] represents a directed route from city a to B.

This year, there will be a big competition in city 0. Many tourists want to go to city 0.

Please help to reorient the route so that each city can access City 0. Returns the minimum number of routes to change direction.

Topic data ensures that each city can reach city 0 after re planning the route direction.

Example 1:

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
 Explanation: change the direction of the route shown in red so that each city can reach city 0.

Example 2:

Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
 Explanation: change the direction of the route shown in red so that each city can reach city 0.

Example 3:

Input: n = 3, connections = [[1,0],[2,0]]
Output: 0

Tips:

  • 2 <= n <= 5 * 10^4
  • connections.length == n-1
  • connections[i].length == 2
  • 0 <= connections[i][0], connections[i][1] <= n-1
  • connections[i][0] != connections[i][1]

Answer 3

BFS + adjacency table

class Solution {
    public int minReorder(int n, int[][] connections) {
        int result = 0;
        Map<Integer, Set<Integer>> conn_idx = new HashMap<>();//index indicating the connection with city i
        boolean[] visited = new boolean[n];//Whether an edge has been accessed
        for(int i = 0; i < connections.length; i++){
            int city1 = connections[i][0];
            int city2 = connections[i][1];
            if(!conn_idx.containsKey(city1)){
                conn_idx.put(city1, new HashSet<>());
            }
            conn_idx.get(city1).add(i);
            if(!conn_idx.containsKey(city2)){
                conn_idx.put(city2, new HashSet<>());
            }
            conn_idx.get(city2).add(i);
        }
        // bfs
        Queue<Integer> queue = new LinkedList<>();
        queue.offer(0);
        while(!queue.isEmpty()){
            int curr = queue.poll();
            // Traverse the connection related to curr through the index of the connection stored above
            for(int i : conn_idx.get(curr)){
                if(visited[i]){
                    continue;
                }
                visited[i] = true;
                int a = connections[i][0];//Start of connection
                int b = connections[i][1];//End of connection
                // If the current point is out, change it to in++
                result += ((a == curr) ? 1 : 0);
                a = ((a == curr) ? b : a);
                queue.offer(a);
            }
        }
        return result;
    }
}

The following solution requires connections to be given in order (just as the test cases of this question are all in order)

class Solution {
    public int minReorder(int n, int[][] connections) {
        Set<Integer> available = new HashSet<>();
        available.add(0);
        int change = 0;
        for(int[] line : connections){
            if(available.contains(line[1])){
                available.add(line[0]);
            }else{
                change++;
                available.add(line[1]);
            }
        }
        return change;
    }
}

1467. The probability that the number of colors of the balls in two boxes is the same

Title Description 4

There are 2n balls with different colors on the table, and there are k colors on the ball. Give you an integer array of balls of size k, where balls[i] is the number of balls of color I.

All the balls have been randomly disordered. The first n balls are placed in the first box, and the last n balls are placed in the other box (please read the explanation of example 2 carefully).

Note: the two boxes are different. For example, if the two ball colors are a and B, and the box colors are [] and (), then the two allocation methods [a] (b) and [b] (a) are different (please read the explanation of example 1 carefully).

Please calculate the probability of "the same number of colors in two boxes".

Example 1:

Input: balls = [1,1]
Output: 1.00000
 Explanation: there are only two ways to distribute the ball equally:
-Put the ball with color 1 into the first box, and the ball with color 2 into the second box
 -Put the ball with color 2 into the first box, and the ball with color 1 into the second box
 For both assignments, the number of colors of the balls in both boxes is the same. So the probability is 2 / 2 = 1.

Example 2:

Input: balls = [2,1,1]
Output: 0.66667
 Explanation: the list of balls is [1, 1, 2, 3]
Random disruption, 12 different disruption schemes with equal probability are obtained, and the probability of each scheme is 1 / 12:
[1,1 / 2,3], [1,1 / 3,2], [1,2 / 1,3], [1,2 / 3,1], [1,3 / 1,2], [1,3 / 2,1], [2,1 / 1,3], [2,1 / 3,1], [2,3 / 1,1], [3,1 / 1,2], [3,1 / 2,1], [3,2 / 1,1]
Then, we put the first two balls in the first box, and the second two balls in the second box.
Eight of the 12 possible random disruptions satisfy the requirement that the number of colors of the balls in two boxes is the same.
Probability = 8 / 12 = 0.66667

Example 3:

Input: balls = [1,2,1,2]
Output: 0.60000
 Explanation: the list of balls is [1, 2, 2, 3, 4, 4]. It's hard to show all 180 random disruption schemes, but it's easier to check only 108 cases of "the same number of colors for the balls in two boxes".
Probability = 108 / 180 = 0.6.

Example 4:

Input: balls = [3,2,1]
Output: 0.30000
 Explanation: the list of balls is [1, 1, 1, 2, 2, 3]. It's hard to show all 60 random disruption schemes, but it's easier to check only 18 cases of "the same number of colors in two boxes".
Probability = 18 / 60 = 0.3.

Example 5:

Input: balls = [6,6,6,6,6,6]
Output: 0.90327

Tips:

  • 1 <= balls.length <= 8
  • 1 <= balls[i] <= 6
  • sum(balls) is even
  • If the error between the answer and the real value is within 10 ^ - 5, it is regarded as the correct answer

Answer 4

Refer to the explanation of y God in station B, the original website https://www.bilibili.com/video/BV1PA411q7c5

class Solution:

    def fact(self, n):
        res = 1
        for i in range(1, n + 1): res *= i
        return res

    def get_tot(self, balls):
        tot = self.fact(sum(balls))
        for b in balls:
            if b:
                tot /= self.fact(b)
        return tot

    def dfs(self, u, balls, left, right, ts, ls, rs):
        if ls * 2 > ts or rs * 2 > ts: return 0
        if u == len(balls):
            l = 0
            r = 0
            for i in range(len(balls)):
                if left[i]: l += 1
                if right[i]: r += 1
            if l != r: return 0
            return self.get_tot(left) * self.get_tot(right)
        res = 0
        for i in range(balls[u] + 1):
            left[u] = i
            right[u] = balls[u] - i
            res += self.dfs(u + 1, balls, left, right, ts, ls + left[u], rs + right[u])
        return res

    def getProbability(self, balls: List[int]) -> float:
        tot = self.get_tot(balls)
        left = [0 for i in range(len(balls))]
        right = [0 for i in range(len(balls))]
        return self.dfs(0, balls, left, right, sum(balls), 0, 0) / tot

  • My official account: sharing LeetCode everyday, let you walk on the road, you can also see algorithm problems on the bus. Welcome to scan code.

Tags: network

Posted on Wed, 10 Jun 2020 02:11:52 -0400 by AnotherQuestion