DEV Community

Cover image for ๐—”๐—ฟ๐—ฟ๐—ฎ๐˜†- ๐—ค๐Ÿฒ ๐— ๐—ฎ๐˜…๐—ถ๐—บ๐˜‚๐—บ ๐—ฆ๐—ฐ๐—ผ๐—ฟ๐—ฒ ๐—ช๐—ผ๐—ฟ๐—ฑ๐˜€ ๐—™๐—ผ๐—ฟ๐—บ๐—ฒ๐—ฑ ๐—ฏ๐˜† ๐—Ÿ๐—ฒ๐˜๐˜๐—ฒ๐—ฟ๐˜€
Pranjal Sailwal
Pranjal Sailwal

Posted on

๐—”๐—ฟ๐—ฟ๐—ฎ๐˜†- ๐—ค๐Ÿฒ ๐— ๐—ฎ๐˜…๐—ถ๐—บ๐˜‚๐—บ ๐—ฆ๐—ฐ๐—ผ๐—ฟ๐—ฒ ๐—ช๐—ผ๐—ฟ๐—ฑ๐˜€ ๐—™๐—ผ๐—ฟ๐—บ๐—ฒ๐—ฑ ๐—ฏ๐˜† ๐—Ÿ๐—ฒ๐˜๐˜๐—ฒ๐—ฟ๐˜€

class Solution {
    public int maxScoreWords(String[] words, char[] letters, int[] score) {
        int[] available = new int[26];
        for (char c : letters) {
            available[c - 'a']++;
        }
        int n = words.length;
        int[] wordScores = new int[n];
        int[][] wordCounts = new int[n][26];
        for (int i = 0; i < n; i++) {
            int wordScore = 0;
            for (char ch : words[i].toCharArray()) {
                wordCounts[i][ch - 'a']++;
                wordScore += score[ch - 'a'];
            }
            wordScores[i] = wordScore;
        }
        int maxScore = 0;
        for (int mask = 0; mask < (1 << n); mask++) {
            int[] totalAvailable = available.clone();
            int currentScore = 0;
            boolean valid = true;
            for (int i = 0; i < n; i++) {
                if ((mask & (1 << i)) != 0) {
                    for (int j = 0; j < 26; j++) {
                        totalAvailable[j] -= wordCounts[i][j];
                        currentScore += wordCounts[i][j] * score[j];
                    }
                }
            }
            for (int count : totalAvailable) {
                if (count < 0) {
                    valid = false;
                    break;
                }
            }
            if (valid) {
                maxScore = Math.max(maxScore, currentScore);
            }
        }
        return maxScore;
    }
}
Enter fullscreen mode Exit fullscreen mode

๐—ข๐—ฝ๐—ฒ๐—ป ๐˜๐—ผ ๐—จ๐—ฝ๐—ฑ๐—ฎ๐˜๐—ฒ๐˜€ ๐—ฎ๐—ป๐—ฑ ๐—ฆ๐˜‚๐—ด๐—ด๐—ฒ๐˜€๐˜๐—ถ๐—ผ๐—ป๐˜€.

Top comments (0)