SEMrush

Program - How to find pair of elements from an array whose sum equals a given number ?




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
private void Demo(int credit, int[] price) {
int max = 0;
for (int i = 0; i < price.length; i++) { if (price[i] > max)
        max = price[i];
    }
    int[] items = new int[max + 1];
    for (int i = 0; i < price.length; i++) {
        items[price[i]]++;
    }
    int num1 = 0, num2 = 0;
    for (int i = 0; i < items.length; i++) { if (items[i] > 0 && credit - i < items.length && items[credit - i] > 0) {
            num1 = items[i] > items[credit - i] ? credit - i : i;
            num2 = items[i] > items[credit - i] ? i : credit - i;
            break;
        }
    }
    int idx1 = -1, idx2 = -1;
    for (int i = 0; i < price.length; i++) {
        if (idx1 <= -1 && num1 == price[i]) {
            idx1 = i++;
        }
        if (idx2 <= -1 && num2 == price[i]) { idx2 = i; } if (idx1 > -1 && idx2 > -1)
            break;
    }
    if (idx2 < idx1) {
        System.out.print(++idx2 + " " + ++idx1);
    } else {
        System.out.print(++idx1 + " " + ++idx2);
    }
    System.out.println();
}

Comments