java - Sum of the maximum downsequence number in an array -
given array
int [] myarray = {5,-11,2,3,14,5,-14,2};
you find maximum sum of values in downsequence in unsorted array of integers. if array of length 0 maxseqvalue must return integer.min_value.
you should print number, 19 because downsequence maximum sum 14,5. downsequence number series of non-increasing number.
these codes used guess there cases still not accounted for. ideas, in advance.
public class maxdownsequence{ public int maxseqvalue(int[] a){ int sum=integer.min_value; int maxsum=integer.min_value; (int i=1;i<a.length;i++){ if(a[i]<a[i-1]){ sum = a[i] + a[i-1]; if (sum>maxsum){ maxsum=sum; } } else { sum=a[i]; if (sum>maxsum){ maxsum=sum; } } } if (a.length==0){ return integer.min_value; } else{ return maxsum; } } public static void main(string args[]){ maxdownsequence myseq = new maxdownsequence(); int [] myarray = {5,-11,2,3,14,5,-14,2}; system.out.println(myseq.maxseqvalue(myarray)); }
}
take input {3,2,1}
answer should 6
program gives 5
.
your approach correct, every time test number in array check if less (actually should <=
) previous array element.
if update sum as: sum = a[i] + a[i-1];
incorrect. sum
in program represents running rum of current subsequence. should not overwriting it.
Comments
Post a Comment