DHPC1702 - Editorial



Author: Adabelle Xie






Given 9 space separated integers, return “Cowboys” or “Lawmen” depending on if the sum of every other integer beginning with the first integer is greater or if the sum of every other integer beginning with the second integer is greater.


Create an integer array arr containing the 9 integers. Make two variables: one to store the Cowboys’ sum C and one to store the Lawmen’s sum L. Run a for loop with counter i. When i is even, add arr[i] to C. When i is odd, add arr[i] to L. Return “Cowboys” if C is greater than L, and return “Lawmen” if L is greater than C.


This strategy, as opposed to running two separate for loops, each incrementing by two, one starting i=0 and one starting i=1, allows us to solve the problem with only one pass through the array and only one loop. Every other element beginning with the first element have even indexes (0, 2, 4, 6, 8). Every other element beginning with the second element have odd indexes (1, 3, 5, 7). Therefore, running a for loop with i simultaneously being the counter and representing the current index in the array allows us to use one loop to solve the problem. We want to keep a running sum for both the Cowboys and the Lawmen. When i is odd we want to add the element in the array at i to the sum for the Lawmen, and vice versa. We can check if i is odd or even with the modulus operator (if i%2 equals 0, i is even, if i%2 equals 1, i is odd). After finishing our running sums, we use a conditional to determine which sum is greater, with two different print statements for each outcome (L greater the C, print “Lawmen”, and vice versa).


Since there are only 9 integers, after putting them in an array, you can hard code the indices that comprise each sum (something like L=arr[1] + arr[3] + arr[5] + arr[7] and C=arr[0] + arr[2] + arr[4] + arr[6] + arr[8]). Then use the same conditional block structure to print the correct statement.


Author’s solution can be found here.