Developing Algorithms Using Arrays

AP Computer Science A· difficulty 3/5

int[] a = {1, 2, 3, 4, 5};
int best = 0;
for (int i = 0; i < a.length; i++) {
  for (int j = i; j < a.length; j++) {
    int s = 0;
    for (int k = i; k <= j; k++) s += a[k];
    if (s > best) best = s;
  }
}

What is best?

  • A

    5

  • B

    9

  • C

    10

  • D

    15

    check_circle

Explanation

The whole array sums to 15, which is the largest contiguous sum.

Want 10 more like this — adaptive to your weak spots?

Related questions