-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSumuptoK.java
More file actions
90 lines (81 loc) · 2.23 KB
/
SumuptoK.java
File metadata and controls
90 lines (81 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package com.ub.codeeval;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SumuptoK {
private void largestIncSubsequence(int array[]) {
//modification of Kanade algorithm for positive numbers
int len = array.length;
int startIndex = 0;
int currentIndex = 0;
int endIndex = 0;
int maxLength = 0;
int currentLength = 0;
for(int i=1;i<len;i++) {
if(array[i] < array[i-1]) {
currentLength = 0;
currentIndex = i;
}else if (array[i] > array[i-1]) {
currentLength += 1;
}
if(currentLength >= maxLength) {
maxLength = currentLength;
endIndex = i;
startIndex = currentIndex;
}
}
System.out.println("The max length = "+maxLength +" within index ("+startIndex +","+endIndex+")");
}
//Largest continuous subsequence
private void largestContinuousSubSeq(int k[]) {
//in O(n)
int maxSum = 0;
int currentSum = 0;
int currentStartIndex = 0;
int startIndex = 0;
int endIndex = 0;
for(int i=0;i<k.length;i++) {
currentSum += k[i];
if(currentSum > maxSum) {
maxSum = currentSum;
startIndex = currentStartIndex;
endIndex = i;
}else if(currentSum <= 0) {
currentSum = k[i];
currentStartIndex = i;
}
}
System.out.println("Longest common sub sequence sum = "+maxSum
+" with interval ("+startIndex+","+endIndex +")");
}
private void findpair(int k[],int sum) {
Arrays.sort(k);
int low = 0;
int high = k.length -1;
List<String> pairs= new ArrayList<String>();
while(low<high) {
int cmpSum = k[low] + k[high];
if (sum < cmpSum) {
high --;
}else if(sum > cmpSum) {
low ++;
}else {
pairs.add(low + "," + high);
high--; //terminating condition
}
}
for(int cnt=0;cnt<pairs.size();cnt++) {
System.out.println(pairs.get(cnt));
}
}
public static void main(String args[]) {
SumuptoK sumk = new SumuptoK();
int arr[] = {55,3,7,12,5,4,6,5,87,12,23,45,46};
sumk.largestIncSubsequence(arr);
int sum = 10;
sumk.findpair(arr, sum);
int arr1[] = {-11,-2,3,-1,2,-9,-4,-5,2,3};
sumk.largestContinuousSubSeq(arr1);
// sumk.largestSubsequence(arr);
}
}