forked from alec121212/AlgorithmsAndAbstractDesign
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram1.java
More file actions
77 lines (70 loc) · 2.58 KB
/
Program1.java
File metadata and controls
77 lines (70 loc) · 2.58 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
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;
class Program1 {
public record Result(int numPlatforms, int totalHeight, int[] numPaintings) {};
/**
* Solution to program 1
*
* @param n number of paintings
* @param W width of the platform
* @param heights array of heights of the paintings
* @param widths array of widths of the paintings
* @return Result object containing the number of platforms, total height of the
* paintings, and the number of paintings on each platform
*/
static Result program1(int n, int W, int[] heights, int[] widths) {
int totalHeight = 0;
int numPlatforms = 0;
List<Integer> paintingsPerPlatform = new ArrayList<>();
int currWidth = 0;
int startIndex = 0;
int counter = 0;
for (int i = 0; i < n; i++) {
if (currWidth + widths[i] <= W) {
// Add painting to current platform
currWidth += widths[i];
counter++;
} else {
// Finish current platform
numPlatforms++;
totalHeight += heights[startIndex]; // Tallest painting is the first one
paintingsPerPlatform.add(counter);
// Start new platform
currWidth = widths[i];
startIndex = i;
counter = 1;
}
}
// Handle the last platform
numPlatforms++;
totalHeight += heights[startIndex];
paintingsPerPlatform.add(counter);
// Convert paintingsPerPlatform to int array
int[] numPaintings = new int[paintingsPerPlatform.size()];
for (int i = 0; i < numPaintings.length; i++) {
numPaintings[i] = paintingsPerPlatform.get(i);
}
return new Result(numPlatforms, totalHeight, numPaintings);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int W = sc.nextInt();
int[] heights = new int[n];
int[] widths = new int[n];
for (int i = 0; i < n; i++) {
heights[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
widths[i] = sc.nextInt();
}
sc.close();
Result result = program1(n, W, heights, widths);
System.out.println(result.numPlatforms);
System.out.println(result.totalHeight);
for (int i = 0; i < result.numPaintings.length; i++) {
System.out.println(result.numPaintings[i]);
}
}
}