import java.util.ArrayList; /** * Created by Arun on 9/11/14. */ public class SequenceResult { public static void maximumContSubSeq(int[] a) { int sum[] = new int[a.length]; // Sum at every element sum[0] = a[0]; int max = 0; for (int i = 1; i < a.length; i++) { sum[i] = Math.max(sum[i - 1] + a[i], a[i]); if(sum[i-1]+a[i]>a[i]){ sum[i] = sum[i - 1] + a[i]; } if (max < sum[i]) { max = sum[i]; } } System.out.println(max); } public static void main(String args[]){ int x[] = {-2, 3, -16, 100, -4, 5, 21 }; maximumContSubSeq(x); } }
Friday, September 12, 2014
Maximum subsequence sum
Program to find whether a number is a perfect square or not
for(int i=1; i<numberToCheck; i++) { if(i*i==numberToCheck) { return true; break; } return false; }The above code can be optimized as follows, since we are sure that the number of times it has to be traversed is less than or equal to half the size of the input number we can divide it by 2.
for(int i=1; i<numberToCheck/2; i++) { if(i*i==numberToCheck) { return true; break; } return false; }Optimized? Not quite... We can still optimize it to <=sqrt(input) number of times!
/** * Created by Arun on 9/12/14. */ public class Square { public static boolean findPerfectSquare(int a) { int currentSquare = 1; for(int i=1;currentSquare<a;i++) { System.out.println(i); if(i*i==a) { return true; } currentSquare = i * i; } return false; } public static void main(String args[]) { System.out.println(findPerfectSquare(1222)); } }
Subscribe to:
Posts (Atom)