The problem: http://codeforces.com/contest/581/problem/B
My code is O(n), and I compared my code with others, cannot understand why my code exceeds the time limit in test case 6 (with n = 100,000)? Any idea?
private void solve() throws IOException {
//String s = nextToken();
int n = nextInt();
int[] array = new int[n];
for (int i = 0; i < n; i++) {
array[i] = nextInt();
}
int max = -1;
String ans = "";
for (int i = array.length-1; i >=0; i--) {
if (array[i] >= max) {
max = array[i];
ans = 0 + " " + ans;
}
else {
ans = ( max - array[i] +1) + " " + ans ;
}
}
writer.println(ans.substring(0,ans.length()-1));
}
Your code is not O(n); + on a String is O(n) and your code is O(n^2). You'd need to use StringBuilder instead.
Additionally, inserting at the beginning instead of the end is also generally bad, so even StringBuilder won't let you do that efficiently.
You'll need to figure out how to build the answer the other way around.
Related
I am trying to determine the algorithmic complexity of this program:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class SuffixArray
{
private String[] text;
private int length;
private int[] index;
private String[] suffix;
public SuffixArray(String text)
{
this.text = new String[text.length()];
for (int i = 0; i < text.length(); i++)
{
this.text[i] = text.substring(i, i+1);
}
this.length = text.length();
this.index = new int[length];
for (int i = 0; i < length; i++)
{
index[i] = i;
}
suffix = new String[length];
}
public void createSuffixArray()
{
for(int index = 0; index < length; index++)
{
String text = "";
for (int text_index = index; text_index < length; text_index++)
{
text+=this.text[text_index];
}
suffix[index] = text;
}
int back;
for (int iteration = 1; iteration < length; iteration++)
{
String key = suffix[iteration];
int keyindex = index[iteration];
for (back = iteration - 1; back >= 0; back--)
{
if (suffix[back].compareTo(key) > 0)
{
suffix[back + 1] = suffix[back];
index[back + 1] = index[back];
}
else
{
break;
}
}
suffix[ back + 1 ] = key;
index[back + 1 ] = keyindex;
}
System.out.println("SUFFIX \t INDEX");
for (int iterate = 0; iterate < length; iterate++)
{
System.out.println(suffix[iterate] + "\t" + index[iterate]);
}
}
public static void main(String...arg)throws IOException
{
String text = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Text String ");
text = reader.readLine();
SuffixArray suffixarray = new SuffixArray(text);
suffixarray.createSuffixArray();
}
}
I have done some research on Wikipedia about the Big-O notation and have run the code with strings of different sizes. Based on the time it takes to run the code with different-size stings, I feel its complexity might be O(n^2). How can I know for sure?
Any help would be greatly appreciated.
The complexity of your createSuffixArray method is O(n^2) and you can determine that by examining the 3 looping blocks. Also, since in your question you said you've read the Wikipedia article covering the Big-O notation, then focus on its properties. They are the core of how to apply the right logic and compute the complexity of an algorithm.
Within your first block, the innermost loop iterating length times is in turn repeated for length times, yielding a complexity of O(n^2) due to the Product Property of the Big-O notation.
for(int index = 0; index < length; index++)
{
String text = "";
for (int text_index = index; text_index < length; text_index++)
{
text+=this.text[text_index];
}
suffix[index] = text;
}
In your second block, although the innermost loop does not perform length iterations at the beginning, its complexity still tends to O(n), producing again an overall complexity of O(n^2) due to the Product Property.
for (int iteration = 1; iteration < length; iteration++)
{
String key = suffix[iteration];
int keyindex = index[iteration];
for (back = iteration - 1; back >= 0; back--)
{
if (suffix[back].compareTo(key) > 0)
{
suffix[back + 1] = suffix[back];
index[back + 1] = index[back];
}
else
{
break;
}
}
suffix[ back + 1 ] = key;
index[back + 1 ] = keyindex;
}
Your third and last block simply iterates length times, giving us a linear complexity of O(n).
for (int iterate = 0; iterate < length; iterate++)
{
System.out.println(suffix[iterate] + "\t" + index[iterate]);
}
At this point to get the method complexity, we need to gather the 3 sub-complexities we've got and apply to them the Sum Property, which will yield O(n^2).
This is for the "Mini Max Sum" problem on HackerRank, I can't see why it doesn't have a check mark on all of the test cases. Can someone tell me where my problem lies at. The question is:
Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than 32 bit integer.)
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
long[] arr = new long[5];
long total = 0, max = 0, min = 0;
for(int arr_i=0; arr_i < 5; arr_i++){
arr[arr_i] = in.nextLong();
min = arr[0];
total += arr[arr_i];
if (arr[arr_i] > max)
max = arr[arr_i];
if (arr[arr_i] <= min)
min = arr[arr_i];
}
System.out.println((total - max) + " " + (total - min));
}
}
This also worked. Thanks!!
static void miniMaxSum(int[] arr) {
List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
Collections.sort(list);
long x=0, y=0;
for(int j=0;j<(list.size()-1);j++){
x = x + list.get(j);
y = y + list.get(j+1);
}
System.out.println(x +" "+y);
}
The problem are the initial values of both min and max.
min is being reset to the first values inside the loop, so it will probably only work if the first or the last value is the minimum one;
max starts with zero, so if all values are negative, max will stay at zero (instead of one of the input values).
Hints: set min and max on the first iteration (i == 0) or, as suggested, use Integer.MAX_VALUE and Integer.MIN_VALUE respectively as initial value (actually long is not needed for min and max, neither is the array)
This is what worked for me in JavaScript:
var sum = 0;
var arry = [];
function miniMaxSum(arr) {
for (var i = 0; i < arr.length; i++) {
for (var j = 0; j < arr.length; j++) {
if (arr[j] !== arr[i]) {
sum += arr[j];
}
}
arry.push(sum);
sum = 0;
}
var min = Math.min(...arry);
var max = Math.max(...arry);
console.log(min, max);
}
static void miniMaxSum(int[] arr) {
int temp = 0;
for (int i = 0; i < arr.length; i++)
{
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
long minSum = 0;
long maxSum = 0;
for(int i = 1; i< arr.length; i++){
maxSum = maxSum + arr[i];
}
for(int i = 0; i< arr.length-1; i++){
minSum = minSum + arr[i];
}
System.out.print(minSum+ " " +maxSum);
}
Worked for me on Python3!
def miniMaxSum(arr):
total = sum(arr)
low = total - min(arr)
high = total - max(arr)
print(high, low)
return
import math
import os
import random
import re
import sys
def miniMaxSum(arr):
arr.sort()
m = sum(arr)
max_num = m - arr[-1]
min_num = m - arr[0]
print(max_num, min_num)
if __name__ == '__main__':
arr = list(map(int, input().rstrip().split()))
miniMaxSum(arr)
This worked for me.
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
import java.util.stream.LongStream;
public class Solution {
// Complete the miniMaxSum function below.
static void miniMaxSum(int[] arr) {
long[] longs = Arrays.stream(arr).asLongStream().toArray();
Arrays.sort(longs);
long sum = LongStream.of(longs).sum();
long min = sum - longs[4];
long max = sum - longs[0];
System.out.println(min + " " + max);
}
private static final Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
int[] arr = new int[5];
String[] arrItems = scanner.nextLine().split(" ");
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");
for (int i = 0; i < 5; i++) {
int arrItem = Integer.parseInt(arrItems[i]);
arr[i] = arrItem;
}
miniMaxSum(arr);
scanner.close();
}
}
Here's a hint in the question: minimum and maximum values that can be calculated by summing exactly four of the five integers.
Just sort the array first, assuming the array is not sorted. Take two for loop because we want to keep the complexity up to O(n) i.e. Linear.
from 1st index to n - 1. Assuming index starts from 0. This will give you sum of all the element except the smallest element which will be the largest sum.
from 0th index to n - 2. Assuming index starts from 0. This will give you sum of all the element except the largest element which will be the least sum.
Let's say, Our initial numbers are 1, 2, 3, 4 and 5.
We can calculate the following sums using four of the five integers:
If we sum everything except 1, our sum is 2 + 3 + 4 + 5 =14.
If we sum everything except 2, our sum is 1 + 3 + 4 + 5 =13.
If we sum everything except 3, our sum is 1 + 2 + 4 + 5 =12.
If we sum everything except 4, our sum is 1 + 2 + 3 + 5 =11.
If we sum everything except 5, our sum is 1 + 2 + 3 + 4 =10.
public static void minmaxsum(int[] ar1) {
long a, b, c, d, e;
a = (long) ar1[1] + (long) ar1[2] + (long) ar1[3] + (long) ar1[4];
System.out.println(a);
b = (long) ar1[0] + (long) ar1[2] + (long) ar1[3] + (long) ar1[4];
System.out.println(b);
c = (long) ar1[0] + (long) ar1[1] + (long) ar1[3] + (long) ar1[4];
System.out.println(c);
d = (long) ar1[0] + (long) ar1[1] + (long) ar1[2] + (long) ar1[4];
System.out.println(d);
e = (long) ar1[0] + (long) ar1[1] + (long) ar1[2] + (long) ar1[3];
System.out.println(e);
long[] df = new long[] { a, b, c, d, e };
long max = df[0];
for (int i = 0; i < df.length; i++) {
if (df[i] > max) {
max = df[i];
}
}
long min = df[0];
for (int i = 0; i < df.length; i++) {
if (df[i] < min) {
min = df[i];
}
}
System.out.println(min + " " + max);
}
This answer is in PYTHON language. I am a beginner and any improvements are welcome
n = input().split(" ")
n=list(n)
n1 = list(map(int,n))
n2 = list(map(int,n))
n1.sort()
n1.pop()
min =0
max=0
for i in n1:
min+=i
n2.sort()
n2.reverse()
n2.pop()
for j in n2:
max+=j
print(min, max)
For an assignment I am doing for one of my classes, we have to implement a Sieve of Eratosthenes. I have tried seven times to get a code that works and have tried incorporating numerous solutions I've researched. I finally have one that will output numbers. Unfortunately, it prints both composite and prime numbers, and doesn't print 2.
My code is as follows:
public class EratosthenesSieveAttempt6 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int limit;
System.out.print("Please enter the highest number to check "
+ "(number must be greater than 2): ");
limit = keyboard.nextInt();
while (limit <= 2){
System.out.println("Error - number must be greater than 2.");
System.out.println("Please enter the highest number to check: ");
limit = keyboard.nextInt();
}
boolean[] numbers = new boolean[limit + 1];
int newPrime = 2;
for(int i = 0; i < limit + 1; i++){
numbers[i] = true;
}
for(int j = 1; j < limit + 1; j++) {
if (j % 2 == 0) {
numbers[j] = false;
}
for(int k = j + 1; k < limit + 1; k++) {
if(numbers[k] == true){
j = k;
System.out.println(k);
}
}
}
}
}
I'm suspecting that there is a problem with my loops. I fixed the i and j variables for my first two loops so that it would print out from 2 onward, the problem seems to be that it's not marking the composite numbers as false after I've initialized the array to true.
Thank you in advance for your help.
Here's an implementation of the Sieve of Eratosthenes I wrote the other day:
import java.util.BitSet;
public static BitSet composite(int max) {
BitSet composite = new BitSet(max);
max = composite.size();
for (int i = 4; i < max; i += 2) composite.set(i, true);
for (int i = 9; i < max; i += 6) composite.set(i, true);
int p = 5;
while (p*p < max) {
if (!composite.get(p)) {
for (int i = p*p; i < max; i += p*2) composite.set(i, true);
}
p += 2;
if (p*p >= max) break;
if (!composite.get(p)) {
for (int i = p*p; i < max; i += p*2) composite.set(i, true);
}
p += 4;
}
return composite;
}
Notes:
BitSet allocates 64-bit words, so the size may be larger than you requested (for example, if you ask it to go up to 1000, it will go up to 1024; that's the reason for max = composite.size() near the top)
Gets the 2's, 3's out of the way explicitly, and then
Relies on the fact that all primes larger than 3 are congruent to either 1 or 5 mod 6; this is the reason the final loop alternates between adding 2 and 4
It returns a BitSet that tells you which numbers are composite. One way to extract just the primes from it would be:
public static int[] primes(BitSet composite) {
int size = composite.size() - 2 - composite.cardinality();
int[] primes = new int[size];
int index = 0;
for (int i = 2; i < composite.size(); i++) {
if (!composite.get(i)) primes[index++] = i;
}
return primes;
}
This is for project euler problem 14.
When a number is even, you're supposed to divide the number by two, but when it is odd you multiply it by three and add one. Eventually it should reach one.
My task is to find the number that takes the largest amount of steps to get to 1.
Here's my code:
int currentNum = 0;
int iterator = 0;
int[] largestChain = new int[]{0,0};
for(int i = 10;i<=1000000;i++)
{
currentNum = i;
iterator = 0;
while(currentNum!=1)
{
iterator++;
if(currentNum%2==0)
{
currentNum/=2;
}
else
{
currentNum = (currentNum*3)+1;
}
}
if(iterator>largestChain[1])
{
largestChain[0] = i;
largestChain[1] = iterator;
}
}
System.out.println("largest iterator:"+largestChain[1]+"for num:"+largestChain[0]);
Can you please help me out by telling me what's slowing it down? (It's taking >30 minutes right now and it still hasn't come up with the answer).
Use long variables instead of int. currentNum goes so high the values wrap around into the negatives!
Once you do that change, your algorithm works just fine. (I tested it)
The reason it take so long is that you are performing this while loop operation on 1 million numbers. The solution to this is to create an algorithm which saves the number of steps dynamically.
int[] steps = new int[1000000];
steps[0] = 0;
steps[1] = 1;
Iterate through the rest of your numbers, adding back to this base case. By the end, many of your paths will be computed, and you will not need a nested loop.
However, if you want to stick to your way:
I'd recommend putting some debug print statements in there to see where it is getting caught up. My guess is that the 1 Million looped while statements are the culprit, but the easiest way to find out is progress check.
try adding System.out.println(i+":"); before the while and System.out.println(" current number: "+currentnum); inside the while.
Should print out something like:
1:
1
2:
2
1
etc.
I modified the code to print the interesting info and how its looping. The loop is crazy.
I would suggest converting currentNum to 'long' and re-run it as that number goes negative (beyond int capacity).
public class TestLoop{
public static void main(String[] args){
int currentNum = 0;
int iterator = 0;
int[] largestChain = new int[]{0,0};
for(int i = 10;i<=1000000;i++)
{
currentNum = i;
iterator = 0;
System.out.println("\nCurrently Running :" + i);
while(currentNum!=1)
{
iterator++;
if(currentNum%2==0)
{
currentNum/=2;
}
else
{
currentNum = (currentNum*3)+1;
}
System.out.print(currentNum + " ");
}
if(iterator>largestChain[1])
{
largestChain[0] = i;
largestChain[1] = iterator;
}
}
System.out.println("\nLargest iterator: "+largestChain[1]+" for num:"+largestChain[0]);
}
}
I ran it on linux and got below answer in 10 mins after I changed the currentNum to 'long'.
Largest iterator: 524 for num:837799
Still there is a flaw in your logic: you are NOT checking if any other number taking the same iterations. E.g. below loop gives two such numbers :
import java.util.ArrayList;
public class TestLoop {
public static void main(String[] args) {
long currentNum;
int iterator;
int[] largestChain = new int[]{0, 0};
ArrayList Nums = new ArrayList();
for (int i = 10; i <= 300; i++) {
currentNum = i;
iterator = 0;
System.out.println("\nCurrently Running :" + i);
while (currentNum != 1) {
iterator++;
if (currentNum % 2 == 0) {
currentNum /= 2;
} else {
currentNum = (currentNum * 3) + 1;
}
System.out.print(currentNum + " ");
}
if (iterator > largestChain[1]) {
largestChain[0] = i;
largestChain[1] = iterator;
Nums.clear();
Nums.add(i);
} else if (iterator == largestChain[1]) {
Nums.add(i);
}
}
System.out.println("\nLargest iterator: " + largestChain[1]);
//+ " for num:" + largestChain[0]);
if (Nums.size() == 1) {
System.out.println("There is only one number with " + largestChain[1] + " iterations:" + largestChain[0]);
} else {
System.out.print("Below numbers took " + largestChain[1] + " iterations:");
for (int i = 0; i < Nums.size(); i++) {
System.out.print(" " + Nums.get(i));
}
}
}
}
Question: what is wrong with my arrays, and how do I fix it?
Details:
I initialized the array in the main method, and the values were set in one method. I called the array values in a 2nd method, and everything was fine.
When I tried to call the array in a 3rd method, I got the out of bounds error, even though the size of the array is exactly the same.
I was trying to call the array in order to copy it, and then sort the 2nd array.
thank you
private static WeatherLocation[] WeatherSpots = new WeatherLocation[6];
private static Scanner Input = new Scanner(System.in);
public static void main(String[] args)
{int Count;
for(Count = 0 ; Count < 6; Count++)
WeatherSpots[Count] = new WeatherLocation();
WeatherSpots[0].LocationID = "Tciitcgaitc";
WeatherSpots[1].LocationID = "Redwood Haven";
WeatherSpots[2].LocationID = "Barrier Mountains";
WeatherSpots[3].LocationID = "Nina's Folly";
WeatherSpots[4].LocationID = "Scooly's Hill";
WeatherSpots[5].LocationID = "Twin Cones Park";
SetUp();
String Command = "";
while(!Command.equals("Quit")) {
Menu();
System.out.print("Enter Command: ");
Command = Input.nextLine();
if(Command.equals("Post"))
PostTemperatureInfo();
if(Command.equals("Daily"))
WeeklyReport();
else if (Command.equals("HighLow"))
Sorting();
}
}
public static void PostTemperatureInfo()
{
Scanner LocalInput = new Scanner(System.in);
int K;
int Temp;
//...then get the values for each location...
System.out.println( "Enter the Temperature for each weather station below:\n");
System.out.println( "---------------------------------------------------------------");
for(K = 0 ; K < 6 ; K++) {
System.out.println( "Weather Station: " + WeatherSpots[K].LocationID); //Display the location of the fishing spot...
System.out.print( "Enter Temperature:\t"); //Get the count...
Temp = LocalInput.nextInt();
System.out.println( "---------------------------------------------------------------");
WeatherSpots[K].CatchCount = Temp;
}
System.out.println("");
System.out.println("");
System.out.println("");
}
public static void WeeklyReport()
{
for(K = 0 ; K < 6 ; K++)
{System.out.println( "" + WeatherSpots[K].LocationID +"\t\t" + WeatherSpots[K].CatchCount + "\t\t" + String.format("%.2f", (WeatherSpots[K].CatchCount - 32) * 5 / 9));
}
}
public static void Sorting()
{int K = 0;
for(K = 0 ; K < 6 ; K++);
{int [] copycat = new int[K];
System.arraycopy(WeatherSpots[K].CatchCount, 0, copycat[K], 0, 6);
System.out.println("" + copycat[K]);
Arrays.sort(copycat, 0, K);
System.out.println("Minimum = " + copycat[0]);
System.out.println("Maximum = " + copycat[K -1]);
}
}
}
The problem is that you are allocating an array copycat that is only K integers long, and then you are trying to fit 6 elements into it, even when K == 0. I don't understand your code enough to figure out what the right indexes are, but that's the source of your problem.
Actually, I don't believe that your code as posted will compile. This line from Sorting():
System.arraycopy(WeatherSpots[K].CatchCount, 0, copycat[K], 0, 6);
seems mighty suspicious. The first and third arguments to System.arraycopy are supposed to be arrays, but copycat[K] is an int. Apparently so is WeatherSpots[K].CatchCount.
EDIT:
It seems from your comments and code that the Sorting() routine is just supposed to print the min and max values of WeatherSpots[K].CatchCount. This can be done much more easily than you are doing. Here's one way:
public static void Sorting() {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (WeatherLocation loc : WeatherSpots) {
final int count = loc.CatchCount;
if (count < min) {
min = count;
}
if (count > max) {
max = count;
}
}
System.out.println("Minimum = " + min);
System.out.println("Maximum = " + max);
}
Q: Why not use "array.length" instead of a hard-coded "6"?
Q: I'd really discourage you from using that indentation style, if you can avoid it.
Anyway - this should work (I have not tried it myself):
public static void Sorting() {
for(int K = 0 ; K < WeatherSpots.length ; K++) {
int [] copycat = new int[K];
System.arraycopy(
WeatherSpots[K].CatchCount, 0, copycat[K], 0, WeatherSpots.length);
System.out.println("" + copycat[K]);
Arrays.sort(copycat, 0, K);
System.out.println("Minimum = " + copycat[0]);
System.out.println("Maximum = " + copycat[K -1]);
}
}
The main thing was to get rid of the extraneous ";" after the "for()" loop.