Question: / * Start with a maximum sum of 0 . Compute the sum of each 1 - element subarray, then compute the sum of each

/* Start with a maximum sum of 0. Compute the sum of each 1-element subarray,
then compute the sum of each 2-element subarray,
then compute the sum of each 3-element subarray, etc. For each sum you compute,
if it is larger than the maximum sum you've seen, then it becomes the maximum sum.*/
public static int algorithm1(int[] nums)
{
int maxSum =0;
for(int i=0;imaxSum){
maxSum = nums[i];
}
}
for(int i=1;imaxSum){
maxSum = newSum;
}
}
for(int i=2;imaxSum){
maxSum = newSum;
}
}
return maxSum;
}
/*Same as algorithm 1, but now once you compute the sum of the subarray from A[i] to A[j],
the sum of the subarray from A[i] to A[j+1] is just the previous sum you computed plus A[j+1].
Don't add up all of the previous values all over again. */
public static int algorithm2(int[] nums)
{
int maxSum =0;
int n = nums.length;
for (int start =0; start < n; start++){
int currentSum =0;
for (int end = start; end < n; end++){
currentSum += nums[end];
if (currentSum > maxSum){
maxSum = currentSum;
}
}
}
is this rigfht is there anything that i can do to make it better

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!