Given an array of n integers. The task is to find the maximum sum of values in a contiguous, nonempty subarray.
Ex:- [ -2 , -5 , 6 , -2 , -3 , 1 , 5 , -6 ]
maxsubarraysum = 7
and subarray is [ 6 , -2 , -3 , 1 , 5 ]
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | import java.util.*; public class MaxSubArraySum{ public static void main(String []args){ Scanner sc = new Scanner(System.in); int size = sc.nextInt(); int ans = Integer.MIN_VALUE, msf = Integer.MIN_VALUE; for(int i=0; i<size; i++){ int num = sc.nextInt(); if(i==0 && num<0) msf = num; else msf = Math.max(num, num+msf); ans = Math.max(ans, msf); } System.out.println("sum:"+ans); } } |
Python
import sys size = int(input()) ans, msf = -sys.maxsize-1, -sys.maxsize-1 for i in range(0,size): num = int(input()) msf = max(num, msf+num) ans = max(msf, ans) print("sum :",ans)