Skip to content

Instantly share code, notes, and snippets.

@gameguy43
Created September 26, 2016 20:23
Show Gist options
  • Save gameguy43/9889a1922401b1b8cabf1e7e288fb7a4 to your computer and use it in GitHub Desktop.
Save gameguy43/9889a1922401b1b8cabf1e7e288fb7a4 to your computer and use it in GitHub Desktop.
translated to c by Maria Maltseva
#include <stdio.h>
#ifndef max
#define max(a,b) ((a) > (b) ? (a) : (b))
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif
int getminElement(int [], int);
int getmaxElement(int [], int);
int highest_product_of_3(int[], int);
///size of array
int size;
/// counter for min and max from arrays fuctions
int i;
int main(){
int size = 3;
///here should be a code to test it
return 0;
}
int highest_product_of_3(int list_of_ints[], int size){
int highest, lowest, highest_product_of_2, lowest_product_of_2, highest_product_of_three;
if (size<3)
{
printf("Less than 3 items!");
return -1;
///We're going to start at the 3rd item (at index 2)
///so pre-populate highests and lowests based on the first 2 items.
///we could also start these as None and check below if they're set
///but this is arguably cleaner
}
highest = max(list_of_ints[0], list_of_ints[1]);
lowest = min(list_of_ints[0], list_of_ints[1]);
highest_product_of_2 = list_of_ints[0] * list_of_ints[1];
lowest_product_of_2 = list_of_ints[0] * list_of_ints[1];
///except this one--we pre-populate it for the first /3/ items.
///this means in our first pass it'll check against itself, which is fine.
highest_product_of_three = list_of_ints[0] * list_of_ints[1] * list_of_ints[2];
///walk through items, starting at index 2
int c;
for (c=2; c < size; c++)
{
///do we have a new highest roduct of 3?
///it's either the current highest,
///or the current times the highest product of two
///or the current times the lowest product of two
int current;
current = list_of_ints[c];
int three[3] = {highest_product_of_three,current * highest_product_of_2,current * lowest_product_of_2};
highest_product_of_three = getmaxElement(three, 3);
/// do we have a new highest product of two?
int three2[3] = {highest_product_of_2,current * highest,current * lowest};
highest_product_of_2 = getmaxElement(three2, 3);
/// do we have a new lowest product of two?
int three3[3] = {lowest_product_of_2,current * highest,current * lowest};
lowest_product_of_2 = getminElement(three3, 3);
/// do we have a new highest?
highest = max(highest, current);
/// do we have a new lowest?
lowest = min(lowest, current);
}
return highest_product_of_three;
}
int getminElement(int a[], int size){
int s = size;
static int i=0,min =1000;
if(i < s){
if(min > a[i])
min=a[i];
i++;
getminElement(a, size);
}
return min;
}
int getmaxElement(int a[], int size){
static int i=0,max =0;
if(i < size){
if(max < a[i])
max=a[i];
i++;
getmaxElement(a, size);
}
return max;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment