Sum of the Leading Small Numbers (takeWhile)
Problem
Read an array and k. Add the numbers from the left side while they are smaller than k. Stop at the first number that is not smaller than k. Print the sum.
Constraints
- 1 <= n <= 10^5
Examples
Input
6 1 2 3 10 1 1 5
Output
6
Solutions
A loop with break is clear and works in every Java version. It is important that the loop stops at the first big number and does not skip it: later small numbers must not be added.
/*
* Problem : Process an array.
* Input : n, n integers, then k.
* Output : The sum of the leading numbers.
* Approach: A loop with break.
* Time : O(n)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(int[] a, int k) {
// Step 1: Add numbers from the left. Stop at the first number that is not smaller than k.
long total = 0;
for (int value : a) {
if (value >= k) {
break;
}
total += value;
}
return total;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] a = new int[size];
for (int i = 0; i < size; i++) {
a[i] = scanner.nextInt();
}
int k = scanner.nextInt();
System.out.println(solve(a, k));
}
}
Hints (1)
- What is the difference between break and continue here?