Created
April 26, 2017 15:38
-
-
Save prateekdwv/64ec7bea4ff2e886e13cc8f6c40f6958 to your computer and use it in GitHub Desktop.
Find the minimum sum of (x+y+z) under the constrain (x+y+z)>=m
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <malloc.h> | |
#include <stdlib.h> | |
#define INF 10000 | |
// Function that is doing the real job | |
int FindTriple(int *, int, int); | |
int main(){ | |
// Size of the array | |
int arrSize; | |
printf("Enter size of array: "); | |
scanf("%d", &arrSize); | |
// Allocate some memory for array | |
int *arr = (int *)malloc(arrSize*sizeof(int)); | |
// And store the elements | |
printf("Enter the elements of array (in sorted order): \n"); | |
for(int i = 0; i < arrSize; i++){ | |
scanf("%d", &arr[i]); | |
} | |
// Constraint x+y+z >= m | |
int m; | |
printf("Required sum of triple: "); | |
scanf("%d", &m); | |
// Hand it over to this function | |
FindTriple(arr, arrSize, m); | |
return 0; | |
} | |
int FindTriple(int *arr, int arrSize, int m){ | |
// If sum of last three element of sorted is smaller than m | |
if(arr[arrSize-3] + arr[arrSize-2] + arr[arrSize-1] < m){ | |
printf("No solution\n"); | |
exit(1); | |
} | |
// Store the value of triple (solution) | |
int x, y, z; | |
// Initialize to Infinity | |
x = y = z = INF; | |
// Iterators | |
int i, j, k; | |
for(i = 0; i < arrSize; i++){ | |
j = i + 1; | |
k = arrSize - 1; | |
while(k > j){ | |
int sum = arr[i] + arr[j] + arr[k]; | |
if(sum == m){ | |
printf("%d + %d + %d = %d\n",arr[i], arr[j], arr[k], sum); | |
return 1; | |
} | |
else if (sum > m){ | |
if(sum < (x+y+z)){ | |
x = arr[i]; | |
y = arr[j]; | |
z = arr[k]; | |
} | |
k = k -1; | |
} | |
else | |
j++; | |
} | |
} | |
printf("%d + %d + %d = %d\n",x, y, z, (x+y+z)); | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment