JAVA | Sliding Window | Sort 2D array
Intuition\nThe data range is [1, 50], we can use a 2D array to store the number and its frequency.\n\nWhen calculate the sum, sort the 2D array on frequency. Re
# Intuition\nThe data range is [1, 50], we can use a 2D array to store the number and its frequency.\n\nWhen calculate the sum, sort the 2D array on frequency. Remember to sort again by number for the following processing.\n\n# Code\n```java []\nclass Solution {\n    public int[] findXSum(int[] nums, int k, int x) {\n        int n = nums.length;\n        int[] res = new int[n - k + 1];\n        int[][] freq = new int[51][2];\n        // store the number in 2D array\n        for (int i = 0; i < 51; i++)\n        \tfreq[i][0] = i;\n        // count the frequency of the first k numbers\n        for (int i = 0; i < k; i++)\n        \tfreq[nums[i]][1]++;\n        res[0] = sum(freq, x);\n        // sliding window\n        for (int i = 1, j = k; j < n; i++, j++) {\n        \tfreq[nums[i - 1]][1]--;\n        \tfreq[nums[j]][1]++;\n        \tres[i] = sum(freq, x);\n        }\n        return res;\n    }\n    int sum(int[][] freq, int x) {\n    \tArrays.sort(freq, (a, b) -> a[1] == b[1] ? b[0] - a[0] : b[1] - a[1]);\n    \tint sum = 0;\n    \tfor (int i = 0; i < x; i++)\n    \t\tsum += freq[i][0] * freq[i][1];\n        Arrays.sort(freq, (a, b) -> a[0] - b[0]);\n    \treturn sum;\n    }\n}\n```
['Java']