DEV Community

Tanuja V
Tanuja V

Posted on β€’ Edited on

3 1

Successful Pairs of Spells and Potions | LeetCode | Java

Approach 1 : Brute Force

This approach will give TLE(Time Limit Exceed). So, it forces us the optimize the solution.

class Solution {
    public int[] successfulPairs(int[] spells, int[] potions, long success) {

        int sLen = spells.length;
        int pLen = potions.length;

        int res[] = new int[sLen];

        for(int i=0; i<sLen; i++){
            int num = spells[i];
            int mul = 0;
            int count = 0;
            for(int j=0; j<pLen; j++){
                mul = num * potions[j];
                if(mul>=success){
                    count++;
                }
                mul = 0;
            }

            res[i] = count;
        }

        return res;
    }
}
Enter fullscreen mode Exit fullscreen mode

Approach 2 : Binary Search

class Solution {
    public int[] successfulPairs(int[] spells, int[] potions, long success) {

        int sLen = spells.length;

        int pLen = potions.length;

        int res[] = new int[sLen];

        Arrays.sort(potions);

        for(int i=0; i<sLen; i++){
            int getCount = getCount(potions, spells[i], pLen, success);
            res[i] = getCount;
        }

        return res;
    }

    int getCount(int potions[], int num, int n, long success){
        int low = 0;
        int high = n-1;
        int mid = 0;

        while(low<=high){
             mid = low + (high-low)/2;

            long mul = (long)num * potions[mid];

            if(mul<success)
                low = mid+1;

            else
                high = mid-1;
        }

        return n-low;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading πŸ₯°
Feel free to comment ✍️
Follow for more 🀝 && Happy Coding πŸš€

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay