اكتب برنامج C لإيجاد الحد الأقصى لمجموع سلسلة مُعطاة من الأرقام

  • برمجة
  • برمجة سي c

اكتب برنامج C لإيجاد الحد الأقصى لمجموع سلسلة مُعطاة من الأرقام :

a1, a2, a3, ... an ( n = عدد العناصر في السلسلة)

إدخال :

1 <= n <= 500 and -10000 <= ai <= 10000

مثال عن الخرج المتوقع :

 

Input number of terms in the sequence:
5

Input the terms of the said sequence:
3
2
6
-7
8
Maximum sum of a contiguous subsequence:
12

الأجوبة

/*Write a C program to find the maximum sum of a contiguous subsequence from a given sequence of numbers a1, a2, a3, ... an ( n = number of terms in the sequence)*/

#include <stdio.h>
int main() {
  int n;
  long a[5000];
  long long max, tmp;
  int i, j;
  printf("Input number of terms in the sequence:\n");
  scanf("%d", & n);
  printf("\nInput the terms of the said sequence:\n");
  for (i = 0; i < n; i++) scanf("%ld", & (a[i]));

  max = a[0];
  tmp = 0;

  for (i = 0; i < n; i++) {
    for (j = i; j < n; j++) {
      tmp += a[j];
      if (max < tmp)
        max = tmp;
    }
    tmp = 0;
  }
  printf("Maximum sum of a contiguous subsequence:\n");
  printf("%lld\n", max);
  return 0;
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...