Design ideas: The user enters an array that is specified as an array of 4 numbers, which can be modified as needed, on how to find the maximum value of the sub-array and the largest: the source array of the maximum value should be first determined to include the maximum value in the original array, so find this maximum value and record the subscript, Defines the two and the variables temp and TEMP1, starting from the maximum subscript one by one summing the comparison and finally getting the largest sum of the subarray.
Source:
Packagearrsum;ImportJava.util.Scanner; Public classSum { Public Static voidMain (string[] args) {intarr[]=New int[10]; intI,sum=arr[0]; intTemp=arr[0]; intTemp2=arr[0]; intMax=arr[0],max1=arr[0]; intMax2=arr[0]; intN; Scanner SC=NewScanner (system.in); System.out.println ("Please enter an array of 4 numbers"); for(i=0;i<4;i++) {Arr[i]=Sc.nextint (); } for(i=0;i<4;i++) { if(arr[i]<arr[i+1]) Max2=arr[i+1]; N=i+1; Temp+=Arr[n]; Temp2+=arr[n+1]; if(temp>temp2) Max=temp; ElseMax1=Temp2; } if(max>max1) Sum=Max; Elsesum=Max1; SYSTEM.OUT.PRINTLN (sum); } }
Results:
Summary: The key to solving the problem is to find out the key to the problem, so in the future programming process I should pay more attention to the full thinking.
To find the maximum value of a subarray