Weekly Contest 297 LeetCode Solution

Problem 1 – Calculate Amount Paid in Taxes Leetcode Solution

You are given a 0-indexed 2D integer array brackets where brackets[i] = [upperi, percenti] means that the ith tax bracket has an upper bound of upperi and is taxed at a rate of percenti. The brackets are sorted by upper bound (i.e. upperi-1 < upperi for 0 < i < brackets.length).

Tax is calculated as follows:

  • The first upper0 dollars earned are taxed at a rate of percent0.
  • The next upper1 - upper0 dollars earned are taxed at a rate of percent1.
  • The next upper2 - upper1 dollars earned are taxed at a rate of percent2.
  • And so on.

You are given an integer income representing the amount of money you earned. Return the amount of money that you have to pay in taxes. Answers within 10-5 of the actual answer will be accepted.

Example 1:

Input: brackets = [[3,50],[7,10],[12,25]], income = 10
Output: 2.65000
Explanation:
The first 3 dollars you earn are taxed at 50%. You have to pay $3 * 50% = $1.50 dollars in taxes.
The next 7 - 3 = 4 dollars you earn are taxed at 10%. You have to pay $4 * 10% = $0.40 dollars in taxes.
The final 10 - 7 = 3 dollars you earn are taxed at 25%. You have to pay $3 * 25% = $0.75 dollars in taxes.
You have to pay a total of $1.50 + $0.40 + $0.75 = $2.65 dollars in taxes.

Example 2:

Input: brackets = [[1,0],[4,25],[5,50]], income = 2
Output: 0.25000
Explanation:
The first dollar you earn is taxed at 0%. You have to pay $1 * 0% = $0 dollars in taxes.
The second dollar you earn is taxed at 25%. You have to pay $1 * 25% = $0.25 dollars in taxes.
You have to pay a total of $0 + $0.25 = $0.25 dollars in taxes.

Example 3:

Input: brackets = [[2,50]], income = 0
Output: 0.00000
Explanation:
You have no income to tax, so you have to pay a total of $0 dollars in taxes.

Constraints:

  • 1 <= brackets.length <= 100
  • 1 <= upperi <= 1000
  • 0 <= percenti <= 100
  • 0 <= income <= 1000
  • upperi is sorted in ascending order.
  • All the values of upperi are unique.
  • The upper bound of the last tax bracket is greater than or equal to income.

Calculate Amount Paid in Taxes Leetcode Solution in C++

double calculateTax(vector<vector<int>>& b, int income) {
    double res = 0, prev = 0;
    for (int i = 0; i < b.size(); prev = b[i++][0])
        res += max(0.0, (-prev + min(income, b[i][0])) * b[i][1] / 100);
    return res;
}

Calculate Amount Paid in Taxes Leetcode Solution in Java

    public double calculateTax(int[][] brackets, int income) {
        double tax = 0;
        int prev = 0;
        for (int[] bracket : brackets) {
            int upper = bracket[0], percent = bracket[1];
            if (income >= upper) {
                tax += (upper - prev) * percent / 100d;
                prev = upper;
            }else {
                tax += (income - prev) * percent / 100d;
                return tax;
            } 
        }
        return tax;
    }

Calculate Amount Paid in Taxes Leetcode Solution in Python 3

    def calculateTax(self, brackets: List[List[int]], income: int) -> float:
        tax = prev = 0
        for upper, p in brackets:
            if income >= upper:
                tax += (upper - prev) * p / 100
                prev = upper
            else:
                tax += (income - prev) * p / 100
                return tax
        return tax    

Calculate Amount Paid in Taxes Leetcode Solution in Python

class Solution:
    def calculateTax(self, brackets: List[List[int]], income: int) -> float:
        taxtot=0
        if(brackets[0][0]<income):
            taxtot+=brackets[0][0]*(brackets[0][1])
            income-=brackets[0][0]
        else:
            taxtot+=income*(brackets[0][1])
            return taxtot/100
        i=1
        while(income>0 and i<len(brackets)):
            if(income>(brackets[i][0]-brackets[i-1][0])):
                taxtot+=(brackets[i][0]-brackets[i-1][0])*brackets[i][1]
                income-=brackets[i][0]-brackets[i-1][0]
            else:
                taxtot+=income*brackets[i][1]
                income=0
            i+=1
        return taxtot/100

Problem 2 – Minimum Path Cost in a Grid Leetcode Solution

You are given a 0-indexed m x n integer matrix grid consisting of distinct integers from 0 to m * n - 1. You can move in this matrix from a cell to any other cell in the next row. That is, if you are in cell (x, y) such that x < m - 1, you can move to any of the cells (x + 1, 0)(x + 1, 1), …, (x + 1, n - 1)Note that it is not possible to move from cells in the last row.

Each possible move has a cost given by a 0-indexed 2D array moveCost of size (m * n) x n, where moveCost[i][j] is the cost of moving from a cell with value i to a cell in column j of the next row. The cost of moving from cells in the last row of grid can be ignored.

The cost of a path in grid is the sum of all values of cells visited plus the sum of costs of all the moves made. Return the minimum cost of a path that starts from any cell in the first row and ends at any cell in the last row.

Example 1:

Input: grid = [[5,3],[4,0],[2,1]], moveCost = [[9,8],[1,5],[10,12],[18,6],[2,4],[14,3]]
Output: 17
Explanation: The path with the minimum possible cost is the path 5 -> 0 -> 1.
- The sum of the values of cells visited is 5 + 0 + 1 = 6.
- The cost of moving from 5 to 0 is 3.
- The cost of moving from 0 to 1 is 8.
So the total cost of the path is 6 + 3 + 8 = 17.

Example 2:

Input: grid = [[5,1,2],[4,0,3]], moveCost = [[12,10,15],[20,23,8],[21,7,1],[8,1,13],[9,10,25],[5,3,2]]
Output: 6
Explanation: The path with the minimum possible cost is the path 2 -> 3.
- The sum of the values of cells visited is 2 + 3 = 5.
- The cost of moving from 2 to 3 is 1.
So the total cost of this path is 5 + 1 = 6.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 2 <= m, n <= 50
  • grid consists of distinct integers from 0 to m * n - 1.
  • moveCost.length == m * n
  • moveCost[i].length == n
  • 1 <= moveCost[i][j] <= 100

Minimum Path Cost in a Grid Leetcode Solution in C++

int minPathCost(vector<vector<int>>& g, vector<vector<int>>& moveCost) {
    int m = g.size(), n = g[0].size();
    vector<vector<int>> dp(m, vector<int>(n, INT_MAX));
    dp[0] = g[0];
    for (int i = 1; i < m; ++i)
        for (int j = 0; j < n; ++j)
            for (int k = 0; k < n; ++k)
                dp[i][k] = min(dp[i][k], g[i][k] + dp[i - 1][j] + moveCost[g[i - 1][j]][k]);
    return *min_element(begin(dp[m - 1]), end(dp[m - 1]));
}

Minimum Path Cost in a Grid Leetcode Solution in Java

    public int minPathCost(int[][] grid, int[][] moveCost) {
        int m = grid.length, n = grid[0].length;
        int[][] cost = new int[m][n];
        for (int c = 0; c < n; ++c) {
            cost[0][c] = grid[0][c];
        }
        for (int r = 1; r < m; ++r) {
            for (int c = 0; c < n; ++c) {
                int mi = Integer.MAX_VALUE;
                for (int j = 0; j < n; ++j) {
                    mi = Math.min(mi, cost[r - 1][j] + moveCost[grid[r - 1][j]][c]);
                }
                cost[r][c] = mi + grid[r][c];
            }
        }
        return IntStream.of(cost[m - 1]).min().getAsInt();
    }

Minimum Path Cost in a Grid Leetcode Solution in Python 3

    def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:
        m, n = map(len, (grid, grid[0]))
        min_cost = 0
        cost = [grid[0][:]]
        for r, row in enumerate(grid):
            if r > 0:
                cost.append([])
                for c, cell in enumerate(row):
                        cost[-1].append(cell + min(cost[-2][j] + moveCost[i][c] for j, i in enumerate(grid[r - 1])))
        return min(cost[-1])            

Minimum Path Cost in a Grid Leetcode Solution in Python

class Solution:
    def minPathCost(self, grid: List[List[int]], moveCost: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        
        @lru_cache()
        def helper(i, j):
            if i == 0:
                return grid[i][j]
            else:
                return grid[i][j] + min(moveCost[grid[i - 1][k]][j] + helper(i - 1, k) for k in range(n))
        
        return min(helper(m - 1, j) for j in range(n))

Problem 3 – Fair Distribution of Cookies Leetcode Solution

You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.

The unfairness of a distribution is defined as the maximum total cookies obtained by a single child in the distribution.

Return the minimum unfairness of all distributions.

Example 1:

Input: cookies = [8,15,10,20,8], k = 2
Output: 31
Explanation: One optimal distribution is [8,15,8] and [10,20]
- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.
The unfairness of the distribution is max(31,30) = 31.
It can be shown that there is no distribution with an unfairness less than 31.

Example 2:

Input: cookies = [6,1,3,2,2,4,1,2], k = 3
Output: 7
Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]
- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.
- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.
- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.
The unfairness of the distribution is max(7,7,7) = 7.
It can be shown that there is no distribution with an unfairness less than 7.

Constraints:

  • 2 <= cookies.length <= 8
  • 1 <= cookies[i] <= 105
  • 2 <= k <= cookies.length

Fair Distribution of Cookies Leetcode Solution in C++

class Solution {
public:
    int ans = INT_MAX;
    void solve(int start, vector<int>& nums, vector<int>& v, int k){
        if(start==nums.size()){
            int maxm = INT_MIN;
            for(int i=0;i<k;i++){
                maxm = max(maxm,v[i]);
            }
            ans = min(ans,maxm);
            return;
        }
        for(int i=0;i<k;i++){
            v[i] += nums[start];
            solve(start+1,nums,v,k);
            v[i] -= nums[start];
        }
    }
    
    int distributeCookies(vector<int>& nums, int k) { // nums is the cookies vector
        int n = nums.size();
        vector<int> v(k,0); // v is to store each sum of the k subsets
        solve(0,nums,v,k);
        return ans;
    }
};

Fair Distribution of Cookies Leetcode Solution in Java

int res = Integer.MAX_VALUE;
public int distributeCookies(int[] cookies, int k) {
    dfs(cookies, 0, k, new int[k]);
    return res;
}

void dfs(int[] cookies, int cur, int k, int[] children) {
    if (cur == cookies.length) {
        int max = 0;
        for (int c : children) max = Math.max(max, c);
        res = Math.min(res, max);
        return;
    }
    for (int i = 0; i < k; i++) {
        children[i] += cookies[cur];
        dfs(cookies, cur + 1, k, children);
        children[i] -= cookies[cur];
    }
}

Fair Distribution of Cookies Leetcode Solution in Python

class Solution:
    def distributeCookies(self, cookies: List[int], k: int) -> int:
        ans = float('inf')
        fair = [0]*k
        def rec(i):
            nonlocal ans,fair
            if i == len(cookies):
                ans = min(ans,max(fair))
                return
			# Bounding condition to stop a branch if unfairness already exceeds current optimal soltution
			if ans <= max(fair):
                return
            for j in range(k):
                fair[j] += cookies[i]
                rec(i+1)
                fair[j] -= cookies[i]
        rec(0)
        return ans

Problem 4 – Naming a Company Leetcode Solution

You are given an array of strings ideas that represents a list of names to be used in the process of naming a company. The process of naming a company is as follows:

  1. Choose 2 distinct names from ideas, call them ideaA and ideaB.
  2. Swap the first letters of ideaA and ideaB with each other.
  3. If both of the new names are not found in the original ideas, then the name ideaA ideaB (the concatenation of ideaA and ideaB, separated by a space) is a valid company name.
  4. Otherwise, it is not a valid name.

Return the number of distinct valid names for the company.

Example 1:

Input: ideas = ["coffee","donuts","time","toffee"]
Output: 6
Explanation: The following selections are valid:
- ("coffee", "donuts"): The company name created is "doffee conuts".
- ("donuts", "coffee"): The company name created is "conuts doffee".
- ("donuts", "time"): The company name created is "tonuts dime".
- ("donuts", "toffee"): The company name created is "tonuts doffee".
- ("time", "donuts"): The company name created is "dime tonuts".
- ("toffee", "donuts"): The company name created is "doffee tonuts".
Therefore, there are a total of 6 distinct company names.

The following are some examples of invalid selections:
- ("coffee", "time"): The name "toffee" formed after swapping already exists in the original array.
- ("time", "toffee"): Both names are still the same after swapping and exist in the original array.
- ("coffee", "toffee"): Both names formed after swapping already exist in the original array.

Example 2:

Input: ideas = ["lack","back"]
Output: 0
Explanation: There are no valid selections. Therefore, 0 is returned.

Constraints:

  • 2 <= ideas.length <= 5 * 104
  • 1 <= ideas[i].length <= 10
  • ideas[i] consists of lowercase English letters.
  • All the strings in ideas are unique.

Naming a Company Leetcode Solution in Python 3

def distinctNames(self, ideas: List[str]) -> int:
        # Group strings by their initials
        A = [set() for _ in range(26)]
        for idea in ideas:
            A[ord(idea[0]) - ord('a')].add(idea[1:])
        
        ans = 0
        # Calculate number of valid names from every initial pair.
        for i in range(25):
            for j in range(i + 1, 26):
                k = len(A[i] & A[j]) # Number of duplicated suffixes
                ans += 2 * (len(A[i]) - k) * (len(A[j]) - k)
        return ans

Naming a Company Leetcode Solution in Java

    public long distinctNames(String[] ideas) {
        HashSet<Integer>[] count = new HashSet[26];
        for (int i = 0; i < 26; ++i)
            count[i] = new HashSet<>();
        for (String s : ideas)
            count[s.charAt(0) - 'a'].add(s.substring(1).hashCode());
        long res = 0;
        for (int i = 0; i < 26; ++i)
            for (int j = i + 1; j < 26; ++j) {
                long c1 = 0, c2 = 0;
                for (int c : count[i])
                    if (!count[j].contains(c)) c1++;
                for (int c : count[j])
                    if (!count[i].contains(c)) c2++;
                res += c1 * c2;
            }
        return res * 2;
    }

Naming a Company Leetcode Solution in C++

    long long distinctNames(vector<string>& ideas) {
        set<string> count[26];
        for (auto& s: ideas)
            count[s[0] - 'a'].insert(s.substr(1));
        long long res = 0;
        for(int i = 0; i < 26; ++i)
            for(int j = i + 1; j < 26; ++j) {   
                long long c1 = 0L, c2 = 0L;
                for (auto& c: count[i])
                    if (!count[j].count(c)) c1++;
                for (auto& c: count[j])
                    if (!count[i].count(c)) c2++;
                res += c1 * c2;
            }
        return res * 2;
    }

Naming a Company Leetcode Solution in Python

    def distinctNames(self, ideas):
        count = defaultdict(set)
        for a in ideas:
            count[a[0]].add(hash(a[1:]))
        res = 0
        for a, seta in count.items():
            for b, setb in count.items():
                if a >= b: continue
                same = len(seta & setb)
                res += (len(seta) - same) * (len(setb) - same)
        return res * 2
Weekly Contest 297 LeetCode Solution Review:

In our experience, we suggest you solve this Weekly Contest 297 LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Weekly Contest 297 LeetCode Solution

Find on LeetCode

Conclusion:

I hope this Weekly Contest 297 LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

LeetCode Solutions

Hacker Rank Solutions

CodeChef Solutions

Leave a Reply

Your email address will not be published.