Write a Java program to find the maximum sum of a contiguous subsequence from a given sequence of numbers a1, a2, a3, ... an. A subsequence of one element is also a continuous subsequence

  • برمجة جافا
  • برمجة

 Write a Java program to find the maximum sum of a contiguous subsequence from a given sequence of numbers a1, a2, a3, ... an. A subsequence of one element is also a continuous subsequence

Input:

You can assume that 1 ≤ n ≤ 5000 and -100000 ≤ ai ≤ 100000.
Input numbers are separated by a space.
Input 0 to exit.

Expected Output:

How many integers would you like to input?
 5
Input the integers:
 25 61 35 42 66
Maximum sum of the said contiguous subsequence:
229             

الأجوبة

 import java.util.*;
public class Main {
	public static void main(String [] args) {
		Scanner s = new Scanner(System.in);
		System.out.println("How many integers would you like to input?");
		    int n = s.nextInt();
			int ans = -100000;
			int acc = 0;
			System.out.println("Input the integers:");
			for (int i=0;i<n;i++) {
				acc += s.nextInt();
				ans = Math.max(ans, acc);
				if (acc < 0) acc = 0;
			}
			System.out.println("Maximum sum of the said contiguous subsequence:");
			System.out.println(ans);
		}
}

Sample Output:

How many integers would you like to input?
 5
Input the integers:
 25 61 35 42 66
Maximum sum of the said contiguous subsequence:
229
هل كان المحتوى مفيد؟

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

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