Home > Software engineering >  Writing a program that reads an array from the console and writes out the subarray that sums to the
Writing a program that reads an array from the console and writes out the subarray that sums to the

Time:11-08

I'm writing a program that's supposed to go through an array and find a subarray/subsequence that adds up to the largest value.

I've run into a few issues and I'm honestly kind of stumped as I'm still pretty fresh to C and coding in general.

I'm having 2 issues right now. One is that I need to have [] around the subarray that gets printed out but whenever I try to do that it puts those brackets around every single element.

The second is that whenever I input the array as [0] I get the subarray 12 which I'm not sure where that's come from. as well as the array [ 10 -1 -2 -1 -1 -1 -1 -1 -1 -1 -1 ] it just returns that the largest sum is 0 from the sub array [-1].

Thanks for the help in advance!

#include <stdio.h>

#define MAX_SIZE 100

int main(void)
{
  int a[MAX_SIZE];
  int N;
  int i;
  int sum = 0;
  int max = 0;
  int begin = 0;
  int end = 0;

  scanf("%d", &N);
  for (i=0;i<N;i  )
    scanf("%d", &a[i]);


  for (int i = 0; i < N; i  ) {
    int sum = 0;
    for (int j = i; j < N; j  ) {
      sum  = a[j];
      if (max < sum) {
        max = sum;
        begin = i;
        end = j;
      }
    }
  }

  printf("Largest sum is %d obtained from the subsequence", max);
  for (i = begin; i <= end; i  ){
    printf(" " "["  "%d"  "] " , a[i]);
  }

  return 0;
}

CodePudding user response:

I think printing the subarray can do like this:

  printf("[");
  for (i = begin; i <= end; i  ){
    printf("%d ", a[i]);
  }
  printf("]");

and for the maximum subarray sum, you can study Kadane’s Algorithm.

CodePudding user response:

I'm afraid we're lacking information. What defines a subarray? How long should/can it be?

We can go down to a length of an array to 1, then the largest element is the largest element in the array

We can go up to length = N-1

And we can use anything in between. So we have a largest sum of an array of length 1 up to N - 1 What should it be?

And where do you want to keep the subsums?

  •  Tags:  
  • c
  • Related