Similar Problems
Similar Problems not available
Find Score Of An Array After Marking All Elements - Leetcode Solution
Companies:
LeetCode: Find Score Of An Array After Marking All Elements Leetcode Solution
Difficulty: Medium
Topics: sorting heap-priority-queue array simulation
Problem:
You are given an integer array nums of size n. The score of an array is defined as follows:
The score is the bitwise XOR of nums[i] and nums[j] where 0 <= i < j < n. Return the maximum score of an array.
Solution:
The problem states that we need to return the maximum score of an array. To find the maximum score, we need to iterate all the possible pairs of elements in the array and take the bitwise XOR of the pair. We will keep track of the maximum score obtained so far.
To solve this problem, we will use the concept of bitwise XOR operation. It returns a binary value that is 1 when the corresponding bits of two operands are different. Otherwise, it returns 0. For example, if we perform a bitwise XOR of 2 and 3, we get 1. The binary representation of 2 is 10, and 3 is 11, so the result is 01.
Algorithm:
- Initialize a variable maxScore to 0.
- Iterate over all the possible pairs of elements in the array.
- Take the bitwise XOR of the pair and store it in a variable tempScore.
- If tempScore is greater than maxScore, update maxScore to tempScore.
- Return maxScore.
Let's write the code for the algorithm:
class Solution {
public:
int maxScore(vector<int>& nums) {
int n = nums.size();
int maxScore = 0;
for(int i=0; i<n-1; i++) {
for(int j=i+1; j<n; j++) {
int tempScore = nums[i] ^ nums[j];
if(tempScore > maxScore)
maxScore = tempScore;
}
}
return maxScore;
}
};
The time complexity of this solution is O(n^2), where n is the length of the array nums. The space complexity is O(1).
Test Cases:
Input: nums = [1,2,4]
Output: 6
Explanation:
The possible pairs of elements are as follows:
(1, 2) -> XOR = 3
(1, 4) -> XOR = 5
(2, 4) -> XOR = 6
The maximum score is 6.
Input: nums = [4,2,1]
Output: 6
Explanation:
The possible pairs of elements are as follows:
(4, 2) -> XOR = 6
(4, 1) -> XOR = 5
(2, 1) -> XOR = 3
The maximum score is 6.
Input: nums = [3,4,5,6,7,8]
Output: 15
Explanation:
The possible pairs of elements are as follows:
(3, 4) -> XOR = 7
(3, 5) -> XOR = 6
(3, 6) -> XOR = 5
(3, 7) -> XOR = 4
(3, 8) -> XOR = 11
(4, 5) -> XOR = 1
(4, 6) -> XOR = 2
(4, 7) -> XOR = 3
(4, 8) -> XOR = 12
(5, 6) -> XOR = 3
(5, 7) -> XOR = 2
(5, 8) -> XOR = 13
(6, 7) -> XOR = 1
(6, 8) -> XOR = 14
(7, 8) -> XOR = 15
The maximum score is 15.
So this is the detailed solution for the "Find Score Of An Array After Marking All Elements" problem on LeetCode.
Find Score Of An Array After Marking All Elements Solution Code
1