Loading

LeetCode problem#2932

Maximum Strong Pair XOR I

Solved in 2 languagesRustJava

Solve it on LeetCode(opens in a new tab)

Solution

26 lines
1impl Solution {
2  pub fn maximum_strong_pair_xor(nums: Vec<i32>) -> i32 {
3      let mut maximum = 0;
4
5      for num1 in &nums {
6          for num2 in &nums {
7              let x: i32 = *num1;
8              let y: i32 = *num2;
9
10              let mut diff = x - y;
11              if diff < 0 {
12                  diff = -diff;
13              }
14              if diff <= std::cmp::min(x, y) {
15                  let xor: i32 = x ^ y;
16
17                  if (xor > maximum) {
18                      maximum = xor;
19                  }
20              }
21          }
22      }
23
24      return maximum;
25  }
26}
1class Solution {
2    public int maximumStrongPairXor(int[] nums) {
3        int maximum = 0;
4
5        for (int i = 0; i < nums.length; i++) {
6            for (int j = 0; j < nums.length; j++) {
7                int x = nums[i];
8                int y = nums[j];
9
10                int diff = x - y;
11                if (diff < 0) { // absolute value
12                    diff = -diff;
13                }
14
15                if (diff <= Math.min(x, y)) {
16                    // a strong pair
17                    int xor = x ^ y;
18                    if (xor > maximum) {
19                        maximum = xor;
20                    }
21                }
22            }
23        }
24
25        return maximum;
26    }
27}

Want a walkthrough of this Rust solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.