Sample Code

GitHub link - UPDATE WITH LINK TO SOLUTION CODE IN REPO

#include <assert.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* readline();
char* ltrim(char*);
char* rtrim(char*);
int parse_int(char*);
/*
* Complete the 'sumCoins' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER price
* 2. INTEGER_ARRAY coins
*/
int sumCoins(int price, int coins_count, int* coins) {
// Go through every possible combination of 3 coins and see if any of them add up to the exact change required
int i = 0;
while (i < coins_count) {
int j = i + 1;
while (j < coins_count) {
int k = j + 1;
while (k < coins_count) {
if (coins[i] + coins[j] + coins[k] == price) {
return 1;
}
k++;
}
j++;
}
i++;
}
return 0;
}
int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");
int p = parse_int(ltrim(rtrim(readline())));
int n = parse_int(ltrim(rtrim(readline())));
int* coins_array = malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
int coins_array_item = parse_int(ltrim(rtrim(readline())));
*(coins_array + i) = coins_array_item;
}
int result = sumCoins(p, n, coins_array);
fprintf(fptr, "%d\n", result);
fclose(fptr);
return 0;
}
char* readline() {
size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);
while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);
if (!line) {
break;
}
data_length += strlen(cursor);
if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') {
break;
}
alloc_length <<= 1;
data = realloc(data, alloc_length);
if (!data) {
data = '\0';
break;
}
}
if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
data = realloc(data, data_length);
if (!data) {
data = '\0';
}
} else {
data = realloc(data, data_length + 1);
if (!data) {
data = '\0';
} else {
data[data_length] = '\0';
}
}
return data;
}
char* ltrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
while (*str != '\0' && isspace(*str)) {
str++;
}
return str;
}
char* rtrim(char* str) {
if (!str) {
return '\0';
}
if (!*str) {
return str;
}
char* end = str + strlen(str) - 1;
while (end >= str && isspace(*end)) {
end--;
}
*(end + 1) = '\0';
return str;
}
int parse_int(char* str) {
char* endptr;
int value = strtol(str, &endptr, 10);
if (endptr == str || *endptr != '\0') {
exit(EXIT_FAILURE);
}
return value;
}