Minimum Dist Between 2 Elements in an given array - c

In a contest, they asked to write a C function which returns the minimum distance between X and Y in the given array, where X and Y are elements of the array Provided X AND Y ARE Distinct.
If have written a piece of code, but that code runs into many if's and else's,
My code (Has Some Bugs):
int getMinXYDist(int arr[],int n,int x,int y){
int i,flag = 0,ele = -1 ,dist = 0;
int minDist = 1000; // SETTING minDist TO MAX VALUE.
for( i = 0 ; i< n; i++)
if(arr[i] == x || arr[i] == y){
if(flag == 0){
flag = 1;
ele = arr[i]==x?x:y;
dist = 0;
}
else{
if(ele == x ){
if(arr[i] == y){
minDist = dist < minDist ? dist : minDist;
dist = 0;
ele = y;
}
else //if(arr[i] == x){
dist = 0;
}
else { //if(ele == y)
if(arr[i] == x){
minDist = dist < minDist ? dist : minDist;
dist = 0;
ele = x;
}
}
}
}
else {
if(flag == 1)
dist++;
}
return minDist;
}
void main(){
int arr = {6,1,5,1,8,6,3,4};
printf("\n%d" ,getMinXYDist(arr,sizeof(arr)/sizeof(int),6,5) ); //Must return 2.
}
Could Any one suggest a smarter way [ Just as in O(n) time complexity ] of calculating the distance?

If x or y is found, record the index it was found at. Once both have been found, each time you find either, compute distance to the last index containing the other value. Update the minimum value if the distance is lower than the previous minimum.
int getMinXYDist(int arr[],int n,int x,int y)
{
int i, indexX, indexY;
int foundX = 0;
int foundY = 0;
int curDist;
int minDist = n;
for (i = 0; i < n; i++)
{
if (arr[i] == x)
{
foundX = 1;
indexX = i;
if (foundX && foundY)
{
curDist = indexX - indexY;
if (curDist < minDist)
{
minDist = curDist;
}
}
}
else if (arr[i] == y)
{
foundY = 1;
indexY = i;
if (foundX && foundY)
{
curDist = indexY - indexX;
if (curDist < minDist)
{
minDist = curDist;
}
}
}
}
return minDist;
}

Basically, I think OP's solution is already optimum, the lower bound for this algorithm is n steps, i.e., done in one iteration.
// if -1 is returned, then none of x and y are in the array
// if n is returned, then one of x and y is not in the array
// otherwise, mindist(x, y) is returned.
int test(int v[], int n, int x, int y)
{
int flag = -1;
int i, a = -1, b = -1, dist = n;
for (i = 0; i < n; ++i) {
if (v[i] == x) {
flag = 0;
a = i;
break;
} else if (v[i] == y) {
flag = 1;
b = i;
break;
}
}
if (flag < 0) return -1; // x and y are both not in array;
for (++i; i < n; ++i) {
if (v[i] == x) {
if (0 == flag) a = i;
else {
flag = 0;
if (i - b < dist) dist = i - b;
a = i;
}
} else if (v[i] == y) {
if (1 == flag) b = i;
else {
flag = 1;
if (i - a < dist) dist = i - a;
b = i;
}
}
}
return dist;
}

int minDistance ( int arr[], int n, int x, int y) {
if(x == y) return 0;
int index1 = -1;
int index2 = -1;
int minvalue = n;
for(int i = 0 ; i < n; i++){
if((arr[i] == x) && ((i-index2) < minvalue)){
index1 = i;
if( index2 != -1)minvalue = i-index2;
}else if((arr[i] == y) && ((i-index1) < minvalue)){
index2 = i;
if( index1 != -1)minvalue = i-index1;
}
}
return minvalue;
}
where
n: size of array.
x and y: two input number of array.
If minvalue returned is n then x or y is not present in array.
complexity: O(n), One Pass.

Related

Optimized Bubble Sort time for sorting int arrays

I'm currently working on an essay, in which I compare sorting times of certain algorithms. I've written an optimized version of bubble sort, which checks if there is a swap, if not, it stops.
void bubble_sort(int* tab, int n) {
int zamiana, x, i;
do {
zamiana = 0;
for (int counter = 0, i = 1; i < n; ++counter, ++i) {
if (tab[counter] > tab[i]) {
x = tab[counter];
tab[counter] = tab[i];
tab[i] = x;
zamiana = 1;
}
}
} while (zamiana != 0);
}
I have found that it takes almost 0s to sort array sorted in ascending order, now I'm testing it on an array sorted in descending order, and times are almost the same as for ascending order. Is it normal?
Code tested:
#include <time.h>
#include <stdio.h>
void quickSort(int* tab, int lewy, int prawy) {
int x, y = lewy - 1, z = prawy + 1, pivot = tab[(lewy + prawy) / 2];
while (1) {
while (pivot < tab[++y]);
while (pivot > tab[--z]);
if (y <= z) {
x = tab[y];
tab[y] = tab[z];
tab[z] = x;
}
else {
break;
}
}
if (z > lewy) {
quickSort(tab, lewy, z);
}
if (y < prawy) {
quickSort(tab, y, prawy);
}
}
void bubble_sort(int* tab, int n) {
int zamiana, x, i;
do {
zamiana = 0;
for (int counter = 0, i = 1; i < n; ++counter, ++i) {
if (tab[counter] > tab[i]) {
x = tab[counter];
tab[counter] = tab[i];
tab[i] = x;
zamiana = 1;
}
}
} while (zamiana != 0);
}
int main (){
int* tab;
int n;
srand(time(NULL));
scanf("%d", &n); //user input array size
tab = (int*)malloc(n * sizeof(int*));
for (int counter = 0; counter < n; ++counter) {
tab[counter] = (rand() % 200) - 100; //<-100;100>
}
quickSort(tab, 0, n); //sorting array to get descending order
clock_t start = clock();
bubble_sort(tab, n); //sorting array
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;
printf("Time elapsed: %f", seconds);
}

why this recursive code only prints one answer?

I made this backtracking recursive code.
this code shows every 4x4 array filled with 1, 2, 3, 4
but no duplication in every one row and line.
but this prints only one answers, what I expected is every answers.
#include <stdio.h>
#include <stdbool.h>
// initializing array
void init_arr(int arr[][4])
{
int x;
int y;
y = 0;
while (y < 4)
{
x = 0;
while (x < 4)
{
arr[y][x] = 0;
x++;
}
y++;
}
}
// check about promising correct
bool promising(int arr[][4], int x, int y)
{
int i;
i = 0;
while (i < 4)
{
if (arr[y][i] == arr[y][x] && i != x)
return (0);
i++;
}
i = 0;
while (i < 4)
{
if (arr[i][x] == arr[y][x] && i != y)
return (0);
i++;
}
return (1);
}
// recursive function
void fill_arr(int arr[][4], int x, int y)
{
int n;
if (x == 0 && y == 0)
init_arr(arr);
if (y == 4)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
printf("\n");
return ;
}
else if (x == 4)
fill_arr(arr, 0, y + 1);
else
{
n = 1;
while (n < 5)
{
arr[y][x] = n;
if (promising(arr, x, y))
fill_arr(arr, x + 1, y);
n++;
}
}
}
int main(void)
{
int arr[4][4];
fill_arr(arr, 0, 0);
return (0);
}
when I put printf in if(promising), this comes out
it looks like some variables are not initializing, but when I put init function to every other line, it getting messier.
Your fill_arr() isn't cleaning up before it leaves.
Add this line before the final brace:
arr[y][x] = 0;

Sudoku solver that returns number of solutions

I made a working sudoku solver using a basic backtracking algorithm.
It works reasonably well even though there are many optimizations to be done.
I tried modifying my code to return the total number of solutions for a given sudoku grid. To do this I simply changed the solving function to add up every possibility instead of stopping at one.
However I only get 1 or 0.
Here is the code for the basic solver:
int check_row(char **tab, int y, int n)
{
int i;
i = 0;
while (i < 9)
{
if (tab[y][i] == n + '0')
return (0);
i++;
}
return (1);
}
int check_column(char **tab, int x, int n)
{
int j;
j = 0;
while (j < 9)
{
if (tab[j][x] == n + '0')
return (0);
j++;
}
return (1);
}
int check_square(char **tab, int x, int y, int n)
{
int i;
int j;
i = (x / 3) * 3;
while (i < (x / 3) * 3 + 3)
{
j = (y / 3) * 3;
while (j < (y / 3) * 3 + 3)
{
if (tab[j][i] == n + '0')
return (0);
j++;
}
i++;
}
return (1);
}
int solve(char **tab, int x, int y)
{
int n;
if (y >= 9 || x >= 9)
return (1);
if (tab[y][x] == '.')
{
n = 1;
while (n < 10)
{
if (check_row(tab, y, n) && check_column(tab, x, n)
&& check_square(tab, x, y, n))
{
tab[y][x] = n + '0';
if (solve(tab, (x + 1) % 9, y + ((x + 1) / 9)))
return (1);
}
n++;
}
tab[y][x] = '.';
return (0);
}
else
return (solve(tab, (x + 1) % 9, y + ((x + 1) / 9)));
}
And here is the modified function that should count the solutions:
int solve_count(char **tab, int x, int y)
{
int n;
int count;
count = 0;
if (y >= 9 || x >= 9)
return (1);
if (tab[y][x] == '.')
{
n = 1;
while (n < 10)
{
if (check_row(tab, y, n) && check_column(tab, x, n)
&& check_square(tab, x, y, n))
{
tab[y][x] = n + '0';
count += solve_count(tab, (x + 1) % 9, y + ((x + 1) / 9));
}
n++;
}
tab[y][x] = '.';
return (count);
}
else
return (solve_count(tab, (x + 1) % 9, y + ((x + 1) / 9)));
}
The main() and helper functions are as follows:
#include <unistd.h>
int solve(char **tab, int x, int y);
int solve_count(char **tab, int x, int y);
void ft_putchar(char c)
{
write(1, &c, 1);
}
void ft_putstr(char *str)
{
int i;
i = 0;
while (*(str + i) != '\0')
{
ft_putchar(*(str + i));
i++;
}
}
void ft_putnbr(int n)
{
int i;
int vect[20];
long nb;
nb = n;
i = -1;
if (nb < 0)
{
ft_putchar('-');
nb = -nb;
}
if (nb == 0)
ft_putchar('0');
while (nb > 0)
{
i++;
vect[i] = nb % 10;
nb = nb / 10;
}
while (i > -1)
{
ft_putchar('0' + vect[i]);
i--;
}
}
int ft_check_input(int argc, char **argv)
{
int i;
int j;
i = 1;
j = 0;
if (argc != 10)
return (1);
while (i < argc)
{
while (argv[i][j])
j++;
if (j != 9)
return (1);
j = 0;
while (argv[i][j] == '.' || (argv[i][j] > '0' && argv[i][j] <= '9'))
j++;
if (j != 9)
return (1);
j = 0;
i++;
}
if (i != 10)
return (1);
else
return (0);
}
void ft_print_sudoku(char **tab)
{
int i;
int j;
i = 1;
j = 0;
while (i < 10)
{
while (j < 9)
{
ft_putchar(tab[i][j]);
if (j < 8)
ft_putchar(' ');
j++;
}
ft_putchar('\n');
j = 0;
i++;
}
}
int main(int argc, char **argv)
{
if (ft_check_input(argc, argv))
ft_putstr("Error: not a good sudoku\n");
else
{
if (solve(argv + 1, 0, 0))
{
ft_print_sudoku(argv);
ft_putnbr(solve_count(argv + 1, 0, 0));
}
else
ft_putstr("Error: no solution\n");
}
return (0);
}
To get the number of solutions for an empty sudoku you would run ('.' means empty item):
./sudoku "........." "........." "........." "........." "........." "........." "........." "........." "........."
It runs, but still stops at the first solution it finds, and returns 1.
What am I missing? I've been scratching my head for a while now.
Eventually I'm thinking of using this function to create a grid by adding random numbers until there's just one solution.
I Did this a long time ago for fun...
What I did to Solve the most difficult ones was to return for each squares, All possible numbers
And then destroy each possible numbers one by one for each grid...
so even if you get 9 possibilities for the first grid you enter the first and if it doesn't fit. you delete it and try the second.
One of them needs too fit :)
To know how may possible solutions to a soduku puzzle exists that would take a brute force calculation.

how to build spiral square matrix using recursion?

I wanted to build a spiral square matrix using recursion. I am able to build spiral square matrix using iterative method as below:
void main()
{
int initial_direction = UP , n = MAX , p = 1 ; /* intial_direction
is set to UP because we need to start moving right */
int r ,c , a[MAX][MAX];
int row_right = 0 , column_down = n-1 , row_left = n-1 , column_up = 0 ;
clrscr ();
//Set all elements of the matrix to 0
for(r = 0 ; r < MAX ; r++)
{
for(c = 0 ; c < MAX ; c++)
a[r][c] = 0 ;
}
//Generate elements of the spiral matrix
while(p != n*n+1)
{
if(initial_direction == UP)
{
//Move RIGHT
r = row_right++ ;
for(c = 0 ; c < n ; c++)
{
if(a[r][c] == 0)
a[r][c] = p++;
}
initial_direction = RIGHT ;
}
else if(initial_direction == RIGHT)
{
//Move down
c = column_down-- ;
for(r = 0 ; r < n ; r++)
{
if(a[r][c] == 0)
a[r][c] = p++;
}
initial_direction = DOWN ;
}
else if(initial_direction == DOWN)
{
//Move left
r = row_left-- ;
for(c = n-1 ; c >= 0 ; c--)
{
if(a[r][c] == 0)
a[r][c] = p++;
}
initial_direction = LEFT ;
}
else if(initial_direction == LEFT)
{
//Move up
c = column_up++;
for(r = n-1 ; r >= 0 ; r--)
{
if(a[r][c] == 0)
a[r][c] = p++;
}
initial_direction = UP ;
}
}
//Print the matrix
printf("\n\n");
for(r = 0 ; r < MAX ; r++)
{
for(c = 0 ; c < MAX ; c++)
printf("%4d ",a[r][c]);
printf("\n");
}
}
I wanted to create the same matrix using recursion:
Here is the code i used:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool s[5][5] = {0};
int counter;
typedef enum {
right = 0,
down,
left,
up
}c_flag;
c_flag flag;
int last;
int build_matrix(int a[5][5],int i,int j, c_flag flag)
{
int ret;
if (i < 0 || i>=5 || j < 0 || j >= 5)
{
if (last == right)
{
flag = down;
last = flag;
}
if (last == down)
{
flag = left;
last = flag;
}
if (last == left)
{
flag = up;
last = flag;
}
if (last == up)
{
flag = left;
last = flag;
}
return false;
}
if (s[i][j] == true)
{
if (last == right)
{
flag = down;
last = flag;
}
if (last == down)
{
flag = left;
last = flag;
}
if (last == left)
{
flag = up;
last = flag;
}
if (last == up)
{
flag = left;
last = flag;
}
return false;
}
if(s[i][j] == false)
{
s[i][j] = true;
a[i][j] = ++ counter;
}
if (flag == right)
{
ret = build_matrix(a,i,j+1,right);
//if (!ret)
// return false;
}
flag = down;
last = flag;
if (flag == down)
{
ret =build_matrix(a,i+1,j,down);
//if (!ret)
// return false;
}
flag = left;
last = flag;
if (flag == left)
{
ret = build_matrix(a,i,j-1,left);
//if (!ret)
// return false;
}
flag = up;
last = flag;
if (flag == up)
{
ret = build_matrix (a,i-1,j,up);
//if (!ret)
// return false;
}
flag = right;
last = flag;
return false;
}
int main()
{
int i, j, n = 5;
int k, ret;
//printf("Enter N to construct square matrix \n");
//scanf("%d",&n);
int a[5][5] = {0};
k = n/2 + n%2;
for (i = 0; i < k; i++)
{
ret = build_matrix(a,i,i,right);
}
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
printf("%d",a[i][j]);
printf("\n");
}
return 0;
}
I am getting out put for above as :
1 2 3 4 5
16 19 22 25 6
15 18 21 24 7
14 17 20 23 8
13 12 11 10 9
instead of
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Problem is Flag is not setting proper, i dunno inside which recursion call flag is getting disturbed.
Please some one help implement using recursion.
#include <stdio.h>
void build_matrix(int msize, int a[msize][msize], int size, int value){
int i, row, col;
if(size < 1)
return;
row = col = (msize - size) / 2;
if(size==1){
a[row][col] = value;
return;
}
for(i=0;i<size-1;++i)
a[row][col++] = value++;//RIGHT
for(i=0;i<size-1;++i)
a[row++][col] = value++;//DOWN
for(i=0;i<size-1;++i)
a[row][col--] = value++;//LEFT
for(i=0;i<size-1;++i)
a[row--][col] = value++;//UP
build_matrix(msize, a, size-2, value);
}
int main(){
int size;
printf("input size : ");
scanf("%d", &size);
int a[size][size];
build_matrix(size, a, size, 1);
for(int r=0;r<size;++r){
for(int c=0;c<size;++c)
printf("%3d ", a[r][c]);
printf("\n");
}
return 0;
}
Working Code, without divide and Just recurse:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 20
bool s[N][N] = {0};
int counter;
typedef enum {
right = 0,
down,
left,
up
}c_flag;
c_flag flag;
int build_matrix(int a[N][N],int i,int j, c_flag flag)
{
int ret;
if (i < 0 || i>=N || j < 0 || j >= N || s[i][j] == true)
return false;
if(s[i][j] == false && a[i][j] == 0)
{
s[i][j] = true;
a[i][j] = ++ counter;
}
if (flag == right)
ret = build_matrix(a,i,j+1,right);
flag = down;
if (flag == down)
ret =build_matrix(a,i+1,j,down);
flag = left;
if (flag == left)
ret = build_matrix(a,i,j-1,left);
flag = up;
if (flag == up)
ret = build_matrix (a,i-1,j,up);
flag = right;
if (flag == right)
ret = build_matrix(a,i,j+1,right);
return false;
}
int main()
{
int i, j;
int k, ret;
//printf("Enter N to construct square matrix \n");
//scanf("%d",&n);
int a[N][N] = {0};
k = N/2 + N%2;
build_matrix(a,i,i,right);
for(i = 0; i < N; i++)
{
for(j = 0; j < N; j++)
{
if (!(a[i][j] < 100))
printf("%3d ",a[i][j]);
else if(a[i][j] < 10)
printf("00%d ",a[i][j]);
else
printf("0%d ",a[i][j]);
}
printf("\n");
}
return 0;
}

Finding a maximum sum contiguous sub array

I am writing a code to find the maximum sum contiguous sub array in C. The logic seems fine according to me, but still the output is not correct. Please look into the code. The algorithm divides a bigger array into 2 sub-arrays. It then checks for maximum sum sub-array by examining the left array , right array and also the array containing the midpoint (It will check right and left from the midpoint and then return the maximum sum sub-array containing the midpoint).
int* cross_max(int arr[], int low, int mid, int high)
{
int left_max, left_sum = -2000;
int sum = 0;
int i;
for(i=mid; i>=low;i--)
{
sum = sum + arr[i];
if(sum > left_sum)
{
left_sum = sum;
left_max = i;
}
}
int right_max, right_sum = -2000;
for(i=mid+1; i<=high;i++)
{
sum = sum + arr[i];
if(sum > right_sum)
{
right_sum = sum;
right_max = i;
}
}
// 0 - sum
// indices - 1,2
int temp_arr[3] = {0,0,0};
temp_arr[0] = left_sum + right_sum;
temp_arr[1] = left_max;
temp_arr[2] = right_max;
int *p = temp_arr;
printf("\n Maximum sum = %d\n",*p);
printf("\n low = %d\n",*(p+1));
printf("\n high = %d\n",*(p+2));
return p;
}
int* find_max(int arr[], int low, int high)
{
int temp_arr[3] = {0,0,0};
if(low == high)
{
temp_arr[0] = arr[low];
temp_arr[1] = low;
temp_arr[2] = low;
int *q = temp_arr;
return q;
}
int mid = (low + high)/2;
int* a1 = find_max(arr,low,mid);
int* a2 = find_max(arr,mid+1,high);
int* a3 = cross_max(arr,low,mid,high);
if (*a1 > *a2 && *a1 > *a3)
return a1;
else if (*a2 > *a1 && *a2 > *a3)
return a2;
else
return a3;
}
int main()
{
int arr[8] = {1,1,2,-2,3,3,4,-4};
int *point = find_max(arr,0,7);
printf("\n Maximum sum = %d\n",*point);
printf("\n low = %d\n",*(point+1));
printf("\n high = %d\n",*(point+2));
return 0;
}
Slightly off-topic, but this problem is well-known for the best way to solve it (in linear time). You can completely derive the code from the specification.
First, define the problem formally:
Given: integer array A[0, N)
Required:
max(0 <= p <= q <= N : sum(p, q))
where sum(p, q) = sum(p <= i < q : A[i])
Approach:
Let X(n) = max(0 <= p <= q <= n : sum(p, q)), then we need to find X(N). We do this by induction:
X(0) = max(0 <= p <= q <= 0 : sum(p, q))
= sum(0, 0)
= sum(0 <= i < 0 : A[i])
= 0
and
X(n+1) = max(0 <= p <= q <= n+1 : sum(p, q))
= max(max(0 <= p <= q <= n : sum(p, q)), max(0 <= p <= n+1 : sum(p, n+1)))
= max(X(n), Y(n+1))
where Y(n) = max(0 <= p <= n : sum(p, n)). We now also determine Y(n) by induction:
Y(0) = max(0 <= p <= 0 : sum(p, 0))
= sum(0, 0)
= 0
and
Y(n+1) = max(0 <= p <= n+1 : sum(p, n+1))
= max(max(0 <= p <= n : sum(p, n+1)), sum(n+1, n+1)))
= max(max(0 <= p <= n : sum(p, n)) + A[n], 0)
= max(Y(n) + A[n], 0)
Code:
Using the analysis above, the code is trivial.
int arr[8] = {1,1,2,-2,3,3,4,-4};
int N = 8;
int x = 0;
int y = 0;
for (int n = 0; n < N; n++) {
y = max(y + arr[n], 0);
x = max(x, y);
}
printf("Maximum sum = %d\n", x);
with
int max(int a, int b) {
if (a > b)
return a;
else
return b;
}
There are a couple of problems with undefined behavior in your code:
The first is that you pass 9 as high which will be used to index the tenth element of an eight-element array. It will be the tenth because in cross_max you loop while i <= high, so you will index arr[9]. Remember that array indexes are from zero to the size minus one (so you can index from 0 to 7 for your array). The indexes out of bounds will contain undefined (i.e. random) values.
The second problem is that you are returning pointers to a local variable from cross_max. This will lead to undefined behavior when you use that returned pointer. Local variables are only valid inside the scope they were declared, and when the function returns the memory area used by the local variables will be reclaimed and used for the next function.
this is helper to get the max value.
int maxcmp(int a, int b) {
return a >= b ? a : b;
}
The idea is as you iterate over the nums, you add them together. If your cur_sum is less than 0 up to that point, you eliminate all the numbers so far. Because adding negative value after that point is not going to increase the total sum for the rest of nums.
int maxSubArray(int* nums, int numsSize){
int maxSoFar = nums[0],
cur_sum = 0;
for(int i = 0; i < numsSize; i++) {
if (cur_sum<0){
cur_sum=0;
}
cur_sum=cur_sum+nums[i];
maxSoFar=maxcmp(maxSoFar,cur_sum);
}
return maxSoFar;
}`enter code here`
The algorithm is not very efficient. The time complexity is o(n^2). Here is a dynamic programming algorithm, which is o(n).
/*************************************************************************
> File Name: subarray.cpp
> Author: luliang
> Mail: lulyon#126.com
> Created Time: 2013/09/10 Tuesday 15:49:23
************************************************************************/
#include <stdio.h>
typedef struct {
int low;
int high;
int sum;
}DPInfoType;
int main()
{
int arr[8] = {1,1,2,-2,3,3,4,-4};
const int n = sizeof(arr) / sizeof(arr[0]);
DPInfoType dp[n];
dp[0].low = 0;
dp[0].high = 0;
dp[0].sum = arr[0];
for(int i = 1; i < n; ++i) {
if(dp[i - 1].sum > 0) {
dp[i].low = dp[i - 1].low;
dp[i].high = i;
dp[i].sum = dp[i - 1].sum + arr[i];
}
else {
dp[i].low = i;
dp[i].high = i;
dp[i].sum = arr[i];
}
}
int max_index = 0;
for(int i = 1; i < n; ++i) {
if(dp[max_index].sum < dp[i].sum) max_index = i;
}
printf("\n Maximum sum = %d\n", dp[max_index].sum);
printf("\n low = %d\n", dp[max_index].low);
printf("\n high = %d\n", dp[max_index].high);
return 0;
}
As already mentioned use of pointers is inappropriate in your code.
This code worked for me.
#include <stdio.h>
#define INF 1000000
int max (int a, int b)
{
if (a < b)
return b;
return a;
}
int findMaxCrossingSubarray (int arr[], int low, int mid, int high, int *start, int *end)
{
int i, left, right;
int max_left, max_right;
int left_sum = -INF;
int sum = 0;
for (i = mid; i >= 0; i--) {
sum += arr[i];
if (sum > left_sum) {
left_sum = sum;
max_left = i;
}
}
int right_sum = -INF;
sum = 0;
for (i = mid + 1; i <= high; i++) {
sum += arr[i];
if (sum > right_sum) {
right_sum = sum;
max_right = i;
}
}
*start = max_left;
*end = max_right;
return left_sum + right_sum;
}
int findMaxSubarray (int arr[], int low, int high, int *start, int *end)
{
if (low == high)
return arr[low];
int mid = (high - low)/2 + low;
int start1, start2, start3;
int end1, end2, end3;
// initialization of start and end for terminal cases.
start1 = start3 = low;
start2 = mid + 1;
end1 = mid;
end2 = end3 = high;
int sum1 = findMaxSubarray(arr, low, mid, &start1, &end1);
int sum2 = findMaxSubarray(arr, mid + 1, high, &start2, &end2);
int sum3 = findMaxCrossingSubarray(arr, low, mid, high, &start3, &end3);
int res = max(max(sum1, sum2), sum3);
if (res == sum1) {
*start = start1;
*end = end1;
}
if (res == sum2) {
*start = start2;
*end = end2;
}
if (res == sum3) {
*start = start3;
*end = end3;
}
return res;
}
int main(int argc, char const *argv[])
{
int size, i, item, result;
printf("Enter the size of array: ");
scanf("%d",&size);
int arr[size];
printf("Enter the array:\n");
for (i = 0; i < size; ++i) {
scanf("%d",&item);
arr[i] = item;
}
int start = 0, end = size-1;
result = findMaxSubarray(arr, 0, size-1, &start, &end);
printf("Result: %d, start: %d and end: %d.\n", result, start, end);
return 0;
}

Resources