Leetcode Weekly Contest 191

1464. Maximum Product of Two Elements in an Array

Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)*(nums[j]-1).

Example 1:

Input: nums = [3,4,5,2]
Output: 12 
Explanation: If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12. 

Example 2:

Input: nums = [1,5,4,5]
Output: 16
Explanation: Choosing the indices i=1 and j=3 (indexed from 0), you will get the maximum value of (5-1)*(5-1) = 16.

Example 3:

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

Constraints:

  • 2 <= nums.length <= 500
  • 1 <= nums[i] <= 10^3
class Solution {
    public int maxProduct(int[] nums) {
        int maxp = 0;
        int count = 0;
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            if (nums[i] == 1)
                count++;
        }
        
        if (count >= len - 1)
            return 0;
        
        for (int i = 0; i < len; i++) {
            for (int j = i + 1; j < len; j++) {
                if (nums[i] == 1 || nums[j] == 1)
                    continue;
                else
                    maxp = Math.max(maxp, (nums[i] - 1) * (nums[j] - 1));
            }
        }
        return maxp;
    }
}

1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts

Given a rectangular cake with height h and width w, and two arrays of integers horizontalCuts and verticalCuts where horizontalCuts[i] is the distance from the top of the rectangular cake to the ith horizontal cut and similarly, verticalCuts[j] is the distance from the left of the rectangular cake to the jth vertical cut.

Return the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays horizontalCuts and verticalCutsSince the answer can be a huge number, return this modulo 10^9 + 7.

 

Example 1:

Input: h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
Output: 4 
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.

Example 2:

Input: h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
Output: 6
Explanation: The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.

Example 3:

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

Constraints:

  • 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
  • It is guaranteed that all elements in horizontalCuts are distinct.
  • It is guaranteed that all elements in verticalCuts are distinct.
class Solution {
    public int maxArea(int h, int w, int[] horizontalCuts, int[] verticalCuts) {
        
        Arrays.sort(horizontalCuts);
        Arrays.sort(verticalCuts);
        
        int hc_max = Math.max(horizontalCuts[0], h - horizontalCuts[horizontalCuts.length - 1]);
        int vc_max = Math.max(verticalCuts[0], w - verticalCuts[verticalCuts.length - 1]);
        
        
        for (int i = 0; i < horizontalCuts.length - 1; i++) {
            hc_max = Math.max(hc_max, horizontalCuts[i + 1] - horizontalCuts[i]);
        }
        
        for (int i = 0; i < verticalCuts.length - 1; i++) {
            vc_max = Math.max(vc_max, verticalCuts[i + 1] - verticalCuts[i]);
        }
        
        return (int)((long) hc_max * vc_max % 1000000007);
        // (long) hc_max * vc_max % 1000000007 会出错,因为在运算结果转换为long之前就已经出现整数溢出了。

    }
}

1466. Reorder Routes to Make All Paths Lead to the City Zero

There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.

Roads are represented by connections where connections[i] = [a, b] represents a road from city a to b.

This year, there will be a big event in the capital (city 0), and many people want to travel to this city.

Your task consists of reorienting some roads such that each city can visit the city 0. Return the minimum number of edges changed.

It's guaranteed that each city can reach the city 0 after reorder.

 

Example 1:

Input: n = 6, connections = [[0,1],[1,3],[2,3],[4,0],[4,5]]
Output: 3
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).

Example 2:

Input: n = 5, connections = [[1,0],[1,2],[3,2],[3,4]]
Output: 2
Explanation: Change the direction of edges show in red such that each node can reach the node 0 (capital).

Example 3:

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

Constraints:

  • 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]

https://leetcode.com/problems/reorder-routes-to-make-all-paths-lead-to-the-city-zero/discuss/661672/C%2B%2BJava-Track-Direction

class Solution {
    public int minReorder(int n, int[][] connections) {
        List<List<Integer>> rodes = new ArrayList<>();
        for (int i = 0; i < n; i++)
            rodes.add(new ArrayList<>());
        
        for (var v : connections) {
            rodes.get(v[0]).add(v[1]);
            rodes.get(v[1]).add(-v[0]);
        }
        
        return dfs(rodes, new boolean[n], 0);
    }
    
    public int dfs(List<List<Integer>> rodes, boolean[] visited, int start) {
        int change = 0;
        visited[start] = true;
        
        for (var end : rodes.get(start)) {
            if (!visited[Math.abs(end)]) {
                change += dfs(rodes, visited, Math.abs(end)) + (end > 0 ? 1 : 0);
            }
        }
        return change;
    }
}

1467. Probability of a Two Boxes Having The Same Number of Distinct Balls

Given 2n balls of k distinct colors. You will be given an integer array balls of size k where balls[i] is the number of balls of color i

All the balls will be shuffled uniformly at random, then we will distribute the first n balls to the first box and the remaining n balls to the other box (Please read the explanation of the second example carefully).

Please note that the two boxes are considered different. For example, if we have two balls of colors a and b, and two boxes [] and (), then the distribution [a] (b) is considered different than the distribution [b] (a) (Please read the explanation of the first example carefully).

We want to calculate the probability that the two boxes have the same number of distinct balls.

Example 1:

Input: balls = [1,1]
Output: 1.00000
Explanation: Only 2 ways to divide the balls equally:
- A ball of color 1 to box 1 and a ball of color 2 to box 2
- A ball of color 2 to box 1 and a ball of color 1 to box 2
In both ways, the number of distinct colors in each box is equal. The probability is 2/2 = 1

Example 2:

Input: balls = [2,1,1]
Output: 0.66667
Explanation: We have the set of balls [1, 1, 2, 3]
This set of balls will be shuffled randomly and we may have one of the 12 distinct shuffles with equale probability (i.e. 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]
After that we add the first two balls to the first box and the second two balls to the second box.
We can see that 8 of these 12 possible random distributions have the same number of distinct colors of balls in each box.
Probability is 8/12 = 0.66667

Example 3:

Input: balls = [1,2,1,2]
Output: 0.60000
Explanation: The set of balls is [1, 2, 2, 3, 4, 4]. It is hard to display all the 180 possible random shuffles of this set but it is easy to check that 108 of them will have the same number of distinct colors in each box.
Probability = 108 / 180 = 0.6

Example 4:

Input: balls = [3,2,1]
Output: 0.30000
Explanation: The set of balls is [1, 1, 1, 2, 2, 3]. It is hard to display all the 60 possible random shuffles of this set but it is easy to check that 18 of them will have the same number of distinct colors in each box.
Probability = 18 / 60 = 0.3

Example 5:

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

Constraints:

  • 1 <= balls.length <= 8
  • 1 <= balls[i] <= 6
  • sum(balls) is even.
  • Answers within 10^-5 of the actual value will be accepted as correct.

https://leetcode.com/problems/probability-of-a-two-boxes-having-the-same-number-of-distinct-balls/discuss/661723/Struggling-with-probability-problems-Read-this.

class Solution(object):
    def getProbability(self, balls):
        """
        :type balls: List[int]
        :rtype: float
        """
        from math import factorial
        first = {}
        second = {}
        
        self.valid = 0
        self.all = 0
        
        def dfs(i):
            if i == len(balls):
                s1 = sum(first.values())
                s2 = sum(second.values())
                
                if s1 != s2:
                    return 0
                
                prob1 = 1
                for k in first:
                    prob1 *= factorial(first[k])
                p1 = factorial(s1) / prob1
                
                prob2 = 1
                for k in second:
                    prob2 *= factorial(second[k])
                p2 = factorial(s2) / prob2
                
                self.all += p1 * p2
                self.valid += p1 * p2 if len(first) == len(second) else 0
                
            else:
                first[i] = balls[i]
                for _ in range(balls[i] + 1):
                    dfs(i + 1)
                    
                    if i in first:
                        first[i] -= 1
                        if first[i] == 0:
                            del first[i]
                    
                    second[i] = second.get(i, 0) + 1
                    
                del second[i]
                
        dfs(0)
        print(self.valid, self.all)
        return self.valid / self.all

python concise version:

class Solution(object):
    def getProbability(self, balls):
        """
        :type balls: List[int]
        :rtype: float
        """

        first = {}
        second = {}
        self.all = 0
        self.valid = 0
        permutation = lambda n, x : math.factorial(n) / reduce(operator.mul, [math.factorial(i) for i in x.values()])
        def dfs(i, sum1, sum2, color1, color2):
            if i == len(balls):
                if sum1 != sum2:
                    return
                p1, p2 = permutation(sum1, first), permutation(sum2, second)
                self.all += p1 * p2
                self.valid += p1 * p2 * (color1 == color2)
            
            else:
                for j in range(balls[i] + 1):
                    first[i], second[i] = j, balls[i] - j
                    dfs(i + 1, sum1 + j, sum2 + balls[i] - j, color1 + (j != 0), color2 + (balls[i] != j))
            
        dfs(0, 0, 0, 0, 0)
        print(self.valid, self.all)
        return self.valid / self.all

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值