Skip to content

Instantly share code, notes, and snippets.

@sideb0ard
Created October 29, 2017 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sideb0ard/6c3acb5a4f3c6696575c05ea7f16d08a to your computer and use it in GitHub Desktop.
Save sideb0ard/6c3acb5a4f3c6696575c05ea7f16d08a to your computer and use it in GitHub Desktop.
cubic, quadratic and linear ways to solve problem
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
int nums_len = 20;
static int nums[] = {31, -41, 59, 26, -53, 58, 97, -93, -23, 84, 45, 344, -343, -34, 456, 87, 102, -434, 20, 188};
bool is_bigger(int numone, int numtwo)
{
return numtwo > numone ? true : false;
}
int max(int one, int two)
{
if (one > two)
return one;
return two;
}
long get_time_ns()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_nsec;
}
void linear_find()
{
long starttime = get_time_ns();
int maxsofar = 0;
int maxendinghere = 0;
for (int i = 0; i < nums_len; ++i)
{
maxendinghere = max(maxendinghere + nums[i], 0);
maxsofar = max(maxsofar, maxendinghere);
}
long endtime = get_time_ns();
long duration = endtime - starttime;
printf("Linear// Max:%d - took%lu ms\n", maxsofar, duration);
}
void quad_find1()
{
long starttime = get_time_ns();
int maxsofar = 0;
int start, end = 0;
for (int i = 0; i < nums_len; ++i)
{
int sum = 0;
for (int j = i; j < nums_len; ++j)
{
sum += nums[j];
if (is_bigger(maxsofar, sum))
{
start = i;
end = j;
maxsofar = sum;
}
}
}
long endtime = get_time_ns();
long duration = endtime - starttime;
printf("QUAD1//MAX: %d (Found between %d and %d) - took:%lu\n", maxsofar, start, end, duration);
}
void cube_find()
{
long starttime = get_time_ns();
int maxsofar = 0;
int start, end = 0;
for (int i = 0; i < nums_len; ++i)
{
for (int j = i; j < nums_len; ++j)
{
int sum = 0;
for (int k = i; k <= j; ++k)
sum += nums[k];
if (is_bigger(maxsofar, sum))
{
start = i;
end = j;
maxsofar = sum;
}
}
}
long endtime = get_time_ns();
long duration = endtime - starttime;
printf("CUBE//MAX: %d (Found between %d and %d) - took:%lu\n", maxsofar, start, end, duration);
}
int main()
{
cube_find();
quad_find1();
linear_find();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment