mat.c (778B)
1 #include <stdio.h> 2 #include <string.h> 3 #include <stdlib.h> 4 /* MinAvgTwoSlice */ 5 6 int solution(int *, int); 7 8 int 9 main(void) 10 { 11 int A[] = {4, 2, 2, 5, 1, 5, 8}; 12 13 printf("%d\n", solution(A, 7)); 14 15 return 0; 16 } 17 18 int 19 solution(int A[], int N) 20 { 21 int nelem, res; 22 double *R = malloc(N * sizeof(double)); 23 double k, t; 24 for (int i = 0; i < N; i++) 25 R[i] = 0; 26 27 for (int i = 0; i < N; i++) 28 { 29 t = A[i]; 30 nelem = 1; 31 for (int j = i+1; j < N; j++) 32 { 33 t += A[j]; 34 ++nelem; 35 k = (double) t/nelem; 36 if (j == i+1 || R[i] > k) { 37 R[i] = k; 38 } 39 } 40 } 41 42 for (int i = 0; i < (N - 1); i++) { 43 if (i == 0) { 44 k = R[i]; 45 res = i; 46 } 47 else if (R[i] < k) { 48 k = R[i]; 49 res = i; 50 } 51 else if (R[i] == k) { 52 if (i < res) 53 res = i; 54 } 55 } 56 57 free(R); 58 59 return res; 60 }