package jan19;
import java.util.Scanner;
public class BarChart {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Time Complexity: O(1), initializing the scanner takes constant time.
// Space Complexity: O(1), using a constant amount of space for the scanner object.
int n = scanner.nextInt();
// Time Complexity: O(1), reading a single integer.
// Space Complexity: O(1), storing a single integer.
int[] arr = new int[n];
// Time Complexity: O(1), declaring the array.
// Space Complexity: O(n), an array of size n is created.
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
// Time Complexity: O(n), iterates over the array to input n elements.
// Space Complexity: O(n), storing n integers in the array.
int max = findMaxValue(arr);
// Time Complexity: O(n), calling findMaxValue, which iterates over the array once.
// Space Complexity: O(1), storing the maximum value (single integer).
for (int i = max; i > 0; i--) {
for (int j = 0; j < n; j++) {
if (i <= arr[j]) System.out.print(" * ");
else System.out.print(" ");
}
System.out.println();
}
// Time Complexity: O(n * max), The outer loop runs 'max' times and the inner loop runs 'n' times.
// Space Complexity: O(1), only printing and no additional space is used apart from loop variables.
}
public static int findMaxValue(int[] arr) {
int max = arr[0];
// Time Complexity: O(1), initialization takes constant time.
// Space Complexity: O(1), storing a single value.
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// Time Complexity: O(n), iterating through the array once to find the maximum value.
// Space Complexity: O(1), only storing a single integer for the max value.
}
/*
Case Time Complexity (TC) Space Complexity (SC)
Best Case O(n * max) O(n)
Average Case O(n * max) O(n)
Worst Case O(n * max) O(n)
*/
Sunday, January 30, 2022
Bar Chart
Subscribe to:
Post Comments (Atom)
Diagonal Traversal
eg. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 1 6 11 16 2 7 12 3 8 4 Approach:...
-
https://leetcode.com/problems/reverse-integer/description/ Integer.MAX_VALUE = 2,147,483,647 = 2 31 - 1 Integer.MIN_VALUE = -2,147,483,64...
-
https://leetcode.com/problems/two-sum/description/ Given the constraints: 2 <= nums.length <= 10⁴ -10⁹ <= nums[i] <= 10⁹ -10...
-
For this particular question, we only have the In - region. So, the code looks like : package pep.Day7 ; public class TowerOfHanoi { p...
No comments:
Post a Comment