LeetCode 2346: Compute the Rank as a Percentage Solution

Master LeetCode problem 2346 (Compute the Rank as a Percentage), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2346. Compute the Rank as a Percentage

Medium

Problem Explanation

Explanation:

To compute the rank as a percentage, we need to first calculate the percentage of a particular value among a list of values. The percentage can be calculated using the formula: (value / total) * 100. We can then find the rank of this percentage among the list of percentages.

Here's the step-by-step algorithm:

  1. Calculate the percentage of the given value among the list of values.
  2. Calculate the percentage for each value in the list and store them in an array.
  3. Sort the array of percentages in descending order to find the rank.
  4. Find the rank of the given value among the sorted array.

Time complexity: O(n log n) - for sorting the array of percentages Space complexity: O(n) - for storing the array of percentages

:

Solution Code

import java.util.Arrays;

class Solution {
    public double computeRankAsPercentage(int[] values, int value) {
        double[] percentages = new double[values.length];
        double targetPercentage = (double)value / Arrays.stream(values).sum() * 100;
        
        for (int i = 0; i < values.length; i++) {
            percentages[i] = (double)values[i] / Arrays.stream(values).sum() * 100;
        }
        
        Arrays.sort(percentages);
        int rank = Arrays.binarySearch(percentages, targetPercentage);
        
        return (double)(rank + 1) / values.length * 100;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2346 (Compute the Rank as a Percentage)?

This page provides optimized solutions for LeetCode problem 2346 (Compute the Rank as a Percentage) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2346 (Compute the Rank as a Percentage)?

The time complexity for LeetCode 2346 (Compute the Rank as a Percentage) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2346 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2346 in Java, C++, or Python.

Back to LeetCode Solutions