Created
September 24, 2016 13:45
-
-
Save nichtemna/3446b2c5cf8570932ab413b3615bfa12 to your computer and use it in GitHub Desktop.
Given a list of numbers, write a function that would return the consecutive sequence of that list that sums up to a specific number.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.util.Queue; | |
import java.util.Scanner; | |
/** | |
* Given a list of numbers, write a function that would return | |
* the consecutive sequence of that list that sums up to a specific number. | |
* If no such sequence return -1. | |
Input | |
9 9 | |
1 1 1 1 1 1 1 1 5 | |
Output | |
1 1 1 1 5 | |
*/ | |
public class SequenceSum { | |
public static void main(String[] args) { | |
Scanner scanner = new Scanner(System.in); | |
int n = scanner.nextInt(); | |
int m = scanner.nextInt(); | |
int[] array = new int[n]; | |
for (int i = 0; i < array.length; i++) { | |
array[i] = scanner.nextInt(); | |
} | |
System.out.print(getSequence(array, m)); | |
} | |
private static String getSequence(int[] array, int m) { | |
Queue<Integer> q = new LinkedList<>(); | |
int sum = 0; | |
for (int i = 0; i < array.length; i++) { | |
q.add(array[i]); | |
sum += array[i]; | |
while (sum > m) { | |
sum -= q.poll(); | |
} | |
if (sum == m) { | |
StringBuilder builder = new StringBuilder(); | |
while (q.size() > 0) { | |
builder.append(q.poll()).append(" "); | |
} | |
return builder.toString(); | |
} | |
} | |
return "-1"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment