Hackerrank | Mini-Max Sum


Link


https://www.hackerrank.com/challenges/mini-max-sum/problem

Problem



Code


5つの要素に4つの要素のみを追加して、最小値と最大値の問題を検索します.
ソート後、前から4個/後ろから4個の値を出力すればよい.
ここで追加するときは大きな数に注意するのでminiとmax値のデータ型はlong longとして指定します
出力も%ldでスケールします.
#include <assert.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** split_string(char*);
int compare(const void* a, const void* b);

// Complete the miniMaxSum function below.
void miniMaxSum(int arr_count, int* arr) {
	long long mini = 0, max = 0;
	int temp = 0;

	qsort(arr, arr_count, sizeof(int), compare);

	for (int i = 0; i < 4; i++)
		mini += arr[i];

	for (int i = 4; i > 0; i--)
		max += arr[i];

	printf("%ld %ld", mini, max);
}

int main()
{
	char** arr_temp = split_string(readline());

	int* arr = malloc(5 * sizeof(int));

	for (int i = 0; i < 5; i++) {
		char* arr_item_endptr;
		char* arr_item_str = *(arr_temp + i);
		int arr_item = strtol(arr_item_str, &arr_item_endptr, 10);

		if (arr_item_endptr == arr_item_str || *arr_item_endptr != '\0') { exit(EXIT_FAILURE); }

		*(arr + i) = arr_item;
	}

	int arr_count = 5;

	miniMaxSum(arr_count, arr);

	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; }

		size_t new_length = alloc_length << 1;
		data = realloc(data, new_length);

		if (!data) { break; }

		alloc_length = new_length;
	}

	if (data[data_length - 1] == '\n') {
		data[data_length - 1] = '\0';
	}

	data = realloc(data, data_length);

	return data;
}

char** split_string(char* str) {
	char** splits = NULL;
	char* token = strtok(str, " ");

	int spaces = 0;

	while (token) {
		splits = realloc(splits, sizeof(char*) * ++spaces);
		if (!splits) {
			return splits;
		}

		splits[spaces - 1] = token;

		token = strtok(NULL, " ");
	}

	return splits;
}

int compare(const void* a, const void* b)    
{
	int num1 = *(int*)a;    
	int num2 = *(int*)b;    

	if (num1 < num2)    
		return -1;      

	if (num1 > num2)    
		return 1;       

	return 0; 
}

Result