Given an array A of 0s and 1s, we may change up to K values from 0 to 1.
Return the length of the longest (contiguous) subarray that contains only 1s.
Example 1:
Input: A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
Output: 6
Explanation:
[1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
Output: 10
Explanation:
[0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Note:
1 <= A.length <= 20000
0 <= K <= A.length
A[i] is 0 or 1
https://leetcode.com/problems/max-consecutive-ones-iii/
This is the question link. On the first test case, I am getting output 9 but it should be 6. I can't figure out where it is going wrong?
public static int f(int arr[],int n,int tar)
{
int st=0,maxc=0,maxf=0;
//tar=tar+1;
for(int i=0;i<n;i++)
{
int se=i-st-maxc;
if(arr[i]==1)
maxc++;
while(i-st-maxc>tar)
{
maxf=Math.max(maxf, i-st);
st++;
}
}
return maxf+1;
}
public static void main(String[] args)
{
Scanner p=new Scanner(System.in);
int n,target;
n=p.nextInt();
target=p.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=p.nextInt();
}
int ans=f(arr,n,target);
System.out.println(ans);
}
You do not need to provide the size of the array because you can get the size from the array.
If you use better variable names, the readability of the code will be better.
Also, you can use if statements in order to check changed values instead of counting.
This is example of the solution:
public static int longestOnes(int[] A, int K) {
var maxCount = 0;
for (int i = 0; i < A.length; i++) {
var count = 0;
var k = 0;
for (int j = i; j < A.length; j++) {
if (A[j] == 1) {
count++;
}
if (A[j] == 0) {
if (k >= K) {
if (count > maxCount) {
maxCount = count;
}
break;
}
count++;
k++;
}
}
}
return maxCount;
}
Related
I have tried several ways changing my code in LeetCode but I can't find the fix, the challenge is the next one :
<<Count the number of prime numbers less than a non-negative number, n.
Example:
Input: 10
Output: 4
Explanation: There are 4 prime numbers less than 10, they are 2, 3, 5, 7.>>
My proposal code is the next one:
import java.util.Scanner;
class Solution {
public int countPrimes(int n) {
Scanner sc = new Scanner(System.in);
int sum = 0;
int cont = 0;
int prime = 0;
prime = sc.nextInt();
int a[] = new int [prime];
for(int i = 0; i < a.length; i++) {
a[i] = i;
cont = 0;
for(int y = 1; y< a.length; y++) {
if(a[i] % y == 0) {
cont ++;
}
}
if (cont == 2) {
sum ++;
}
}
return sum;
}
}
Meanwhile the error marks as follows:
Submission Result: Compile Error More Details
Line 7: error: cannot find symbol [in __Driver__.java] int ret = new Solution().countPrimes(param_1); ^ symbol: method countPrimes(int) location: class Solution
Run Code Status: Runtime Error
×
Run Code Result:
Your input
10
Your answer
java.util.NoSuchElementException
at line 937, java.base/java.util.Scanner.throwFor
at line 1594, java.base/java.util.Scanner.next
at line 2258, java.base/java.util.Scanner.nextInt
at line 2212, java.base/java.util.Scanner.nextInt
at line 8, Solution.countPrimes
at line 54, __DriverSolution__.__helper__
at line 84, __Driver__.main
Show Diff
Runtime: N/A
Please help!
This'll also pass through:
public class Solution {
public static final int countPrimes(int n) {
// mapping for if the number is divisible by prime numbers, which would make that number a composite number
boolean[] notPrime = new boolean[n];
// counting prime numbers
int count = 0;
for (int i = 2; i < n; i++) {
// If the index of notPrime would be false, we have a prime number, we go through the if, otherwise we continue
if (notPrime[i] == false) {
// Increment the number of prime numbers
count++;
// Look into future numbers
for (int j = 2; i * j < n; j++) {
// find composite numbers and set their indices to true
notPrime[i * j] = true;
}
}
}
return count;
}
}
References
For additional details, you can see the Discussion Board. There are plenty of accepted solutions with a variety of languages and explanations, efficient algorithms, as well as asymptotic time/space complexity analysis1, 2 in there.
Sieve of Eratosthenes
YouTube 1
YouTube 2
You got confused with the input/output part: you don't need any scanner to do this, just:
class Solution
{
public static int countPrimes(int n)
{
int sum = 0;
int a[] = new int [n];
for(int i = 0; i < a.length; i++) {
a[i] = i;
int cont = 0;
for(int y = 1; y< a.length; y++) {
if(a[i] % y == 0) {
cont++;
}
}
if (cont == 2) {
sum++;
}
}
return sum; //this is the output
}
public static void main(String args[])
´{
countPrimes(10); //this is the input
}
}
Proof:
Et voilá. LeetCode accepts the input (10) and the output (4). That's all you need :)
Your answer gets a scanner object which is not needed therefore you could remove it.
You also create an array which will decrease performance, which I recommend not using as you do not need to display the prime numbers but only keep track of them.
public static int countPrimes(int n) {
int sum=0;
for(int i = n; i > 1; i-- ){
int count = 0; //Keep track of the number of primes.
for(int j = 2; j < i; j++){
if(i % j == 0){
count++;
}
}
if(count==0) {
sum++;
}
}
return sum;
}
I've a question to you.
https://stackoverflow.com/questions/14975968/vertical-arrangement-with-asterisk#=
The code which you shared this post is very good. I've an exam tomorrow. May you tell me the solution.
I edited int array in this program.
It's {-1, 2, 5, 3} but program is not printing (-1) value in which int array.
I want to When the loop read this minus value, it cross new line and print "*" and print the minus value to its underline.
Can you tell me how can i do that in Java?
Thank you.
https://i.stack.imgur.com/ESsVE.jpg
public static void main(String[] args) throws IOException {
int[] a = new int[] {-1,3,-4,2,5};
int[] tmp = a.clone();
Arrays.sort(tmp);
int max = tmp[tmp.length-1];
int low = tmp[0];
int last =max;
if(low<0) {
last=max-low;
}
for (int i = 0; i < last+1; i++) {
for (int j = 0; j < a.length; j++) {
if (i == last ) {
System.out.print(a[j]);
} else if(i<max){
if (i < max - a[j])
System.out.print(" ");
else
System.out.print("*");
}
else {
if (i < max - a[j] )
System.out.print("*");
else
System.out.print(" ");
}
}
System.out.println();
}
}
I can't solve the problem , where I need output from array A like {1,2,3,4,-1,-2,-3,-4}
from random numbers in array, then write it to another array B. So far my experimental code doesn't work as I'd
public static void main(String[] args) {
int a[] = {5,4,3,2,1,-3,-2,-30};
int length = a.length - 1;
for (int i = 0 ; i < length ; i++) {
for (int j = 0 ; j < length-i ; j++) {
if (a[j] < a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
}
for (int x : a) {
System.out.print(x+" ");
}
}
Output is 5 4 3 2 1 -2 -3 -30 , but I need 1,2,3,4,5,-2,-3,-30
Update:
public static void main(String[] args) {
int a[] = {5,4,3,2,1,-3,-2,-30,-1,-15,8};
int length = a.length - 1;
for (int i = 0 ; i < length ; i++) {
for (int j = 0 ; j < length-i ; j++) {
if (a[j] < a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
} else {
if (a[j] > a[j+1] && a[j+1] > 0) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
}
}
for (int x : a) {
System.out.print(x+" ");
}
}
I got closer to my target but 8 1 2 3 4 5 -1 -2 -3 -15 -30 , that number 8 ruins it all
Add an if-else to differentiate the positive and negative case.
if (a[j] < 0) {
if (a[j] < a[j+1]) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
} else {
if (a[j] > a[j+1] && a[j+1] > 0) {
int swap = a[j];
a[j] = a[j+1];
a[j+1] = swap;
}
}
If I understand you correctly you want to sort after two things. Positive numbers from low to high and negative numbers from high to low.
You could first sort from high to low and in a second run over the array skip all positives and then sort from high to low.
Does this help?
I could write some code, but I believe that's something you want to learn right now :)
Algo:
Traverse the Array and Store positives in one and Negatives in another. O(i)
Sort the positives array in ascending order. O(mLog(m))
Sort the negatives indescending order. O(nLog(n))
Create a final array of the size of the input.
Add all the positive array sorted values. Then add the negative array sorted values. O(i)
Total : O(i) + O(mLog(m)) + O(nLog(n)) + O(i) = O(mLog(m)) if m > n
I have used library functions here. But if you want you can the write the functions using the same idea.
public class PostivieAsendingNegativeDesending implements Comparator<Integer> {
public static void main(String args[]) {
int fullList[] = {5, 4, 3, 2, 1, -3, -2, -30};
ArrayList<Integer> subList = new ArrayList<>();
ArrayList<Integer> subList2 = new ArrayList<>();
for (int i = 0; i < fullList.length; i++) {
if (fullList[i] < 0) {
subList2.add((fullList[i]));
} else {
subList.add(fullList[i]);
}
}
Collections.sort(subList);
Collections.sort(subList2, new PostivieAsendingNegativeDesending());
subList.addAll(subList2);
for (int i = 0; i < subList.size(); i++) {
System.out.print(subList.get(i) + " ");
}
System.out.println("");
}
#Override
public int compare(Integer n1, Integer n2) {
return n2 - n1;
}
}
This will do the trick which uses only basic loops
public static void main(String[] args) {
int a[] = { 5, 4, 3, 2, 1, -3, -2, -30 };
int length = a.length - 1;
int pos = 0, neg = 0;
// find total count of positive and negative numbers
for (int i = 0; i <= length; i++) {
if (a[i] < 0)
neg++;
else
pos++;
}
// initialize the arrays based on 'pos' and 'neg'
int posArr[] = new int[pos];
int negArr[] = new int[neg];
// store pos and neg values in the arrays
int countPos = 0, countNeg = 0;
for (int i = 0; i <= length; i++) {
if (a[i] < 0) {
negArr[countNeg] = a[i];
countNeg++;
} else {
posArr[countPos] = a[i];
countPos++;
}
}
// sort positive numbers
for (int i = 0; i < posArr.length - 1; i++) {
for (int j = 0; j < posArr.length - 1 - i; j++) {
if (posArr[j] > posArr[j + 1]) {
int swap = posArr[j];
posArr[j] = posArr[j + 1];
posArr[j + 1] = swap;
}
}
}
// sort negative numbers
for (int i = 0; i < negArr.length - 1; i++) {
for (int j = 0; j < negArr.length - 1 - i; j++) {
if (negArr[j] < negArr[j + 1]) {
int swap = negArr[j];
negArr[j] = negArr[j + 1];
negArr[j + 1] = swap;
}
}
}
// 1. print out posArr[] and then negArr[]
// or
// 2. merge them into another array and print
}
Logic is explained below :
Find total count of positive and negative numbers.
Create and store the positive and negative values in the respective arrays.
Sort positive array in ascending order.
Sort negative array in descending order.
Print out positive array followed by the negative array OR merge them into another and print.
I suggest another approach. You should try to formulate the rules to which the exact comparison must adhere.
Your requirement seem to have the following rules:
Positive numbers always come before negative numbers.
Positive numbers are ordered in ascending order.
Negative numbers are ordered in descending order. Yes, I said descending. Since higher numbers come before lower numbers, i.e. −2 is greater than −7.
Warning: you are using a nested for loop, which means that the process time will grow exponentially if the array becomes larger. The good news is: you don't need to nest a for loop into another for loop. I suggest writing a Comparator instead:
// The contract of Comparator's only method 'compare(i, j)' is that you
// return a negative value if i < j, a positive (nonzero) value if i > j and
// 0 if they are equal.
final Comparator<Integer> c = (i, j) -> { // I'm using a lambda expression,
// see footnote
// If i is positive and j is negative, then i must come first
if (i >= 0 && j < 0) {
return -1;
}
// If i is negative and j is positive, then j must come first
else if (i < 0 && j >= 0) {
return 1;
}
// Else, we can just subtract i from j or j from i, depending of whether
// i is negative or positive
else {
return (i < 0 ? j - i : i - j);
}
}
Your code could look like this:
int[] a = { 5, 4, 3, 2, 1, -3, -2, -30 };
int[] yourSortedIntArray = Arrays.stream(a)
.boxed()
.sorted(c) // Your Comparator, could also added inline, like
// .sorted((i, j) -> { ... })
.mapToInt(i -> i)
.toArray();
Lambda expressions are a new concept from Java 8. The Java Tutorials provide some valuable information.
I tested the program out with 88 and it was left with one star to complete the triangle. 87, two stars 86 three stars. This went on for certain numbers.
These are the two options for programming generate function
• One is to compute the length of the last line, say maxLen, and use a double for-loop to generate a line of one star, a line of two stars, a line of three starts, and so on, ending with a line of maxLen stars. The value of maxLen is the smallest integer that is greater than or equal to the
larger solution of the quadratic equation x ( x + 1 ) = 2 * num.
• The other is to use one for-loop to print num stars while executing System.out.println()wherever the newline is needed. The point at which the newline is needed can be computed using two accompanying integer variables, say len and count. Here the former is the length of the line being generated and the count is the number of stars yet to be printed in the line. We start by setting the value of 1 to both integer variables. At each round of the iteration, we decrease the value of count, if the value of count becomes 0, we insert the newline, increase the value of len and then copy of the value of len to count. When the loop terminates, if the value of count is neither equal to 0 nor equal to count, we extend the present line by adding more stars.
import java.util.*;
public class TriangleSingle
{
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
count = len;
}
}
if (count!= 0 || count != len)
{
System.out.println("*"); //Completes the triangle if needed
// This is the **problem spot**
}
Try this:-
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x; k++)
{
for (int i = 1; i <= k; i++) {
System.out.print("*");
}
System.out.println();
}
}
The trick is to increment the count c of printed stars in the inner loop, which prints each row, but check it against the desired number n in the outer loop, which determines how many rows to print. This way we're sure to print complete rows, but we stop as soon as we've printed at least n stars.
public static void generate(int n)
{
for(int c=0, i=0; c<n; i++)
{
for(int j=0; j<=i; j++, c++)
System.out.print('*');
System.out.println();
}
}
Try this out !!!
public class pyramid {
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Input Length of pyramid : ");
int length = s.nextInt();
for (int i = 1; i <= length; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*\t");
}
System.out.println("\n");
}
}
Check this out :
public static void generate(int x) //Generates the Triangle
{
int len, count;
len = 1;
count = 1;
for (int k = 1; k <= x;)
{
System.out.print("*");
count --;
if (count == 0)
{
System.out.println();
len ++;
k++;
count = len;
}
}
I am new to Java Programming (or programming infact).
I have an array which contains either 4 or 6 only. Given a number, either 4 or 6, find the highest sequential occurrence of the given number.
I need highest sequential occurrence count
Example: arr[{4,4,6,6,4,4,4,4,4,6}]
If the above array is given, and next input number is 4, the output should be 5. Because the number 4 has occurred sequentially 5 times.
public static void main(String[] args) throws IOException {
String arrayTK = br.readLine(); // Input is 4466444446
int[] inpArray = new int[10];
for (int i = 0; i < 10; i++) {
inpArray[i] = arrayTK.charAt(i) - '0';
}
int maxSequenceTimes = 0;
for (int j = 0; j < 10; j++) {
// Logic
}}
Any help would be greatly appreciated.
Edit
We will separate and count all sequences and then search in each sequence to know which sequence contain the biggest length.
int[] arr = {4,4,6,6,4,4,4,4,4,6};
boolean newSeq = false;
int diffrentSeq = 0;
int currentNumber;
//Get sequence numbers
for (int i = 0; i < arr.length; i++) {
currentNumber = arr[i];
if (i >= 1 && currentNumber != arr[i - 1])
newSeq = true;
else if (i == 0)
newSeq = true;
//It's new sequence!!
if (newSeq) {
diffrentSeq++;
newSeq = false;
}
}
System.out.println(diffrentSeq);
int[] maxSequencSize = new int[diffrentSeq];
int lastIndex = 0;
for (int i = 0; i < maxSequencSize.length; i++) {
int currentNum = arr[lastIndex];
for (int j = lastIndex; j < arr.length; j++) {
if (arr[j] == currentNum) {
maxSequencSize[i]++;
lastIndex = j + 1;
} else break;
}
}
System.out.println(max(maxSequencSize));
You need to get max value which act the max sequence length:
private static int max(int[] array){
int maxVal = 0;
for (int anArray : array) {
if (anArray > maxVal)
maxVal = anArray;
}
return maxVal;
}
String arrayTK = br.readLine(); // Input is 4466444446
Because your first input is a string, you don't need to convert it to an int array and if you are using you can use:
String arrayTK = "4466444446";
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream().max(Comparator.comparingInt(String::length)).get().length();
System.out.println(result);
Explanation :
arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2") put a separator between each two different numbers the result should be 44;66;44444;6
.split(";") split with this separator (i used ; in this case) the result is ["44", "66", "44444", "6"]
stream().max(Comparator.comparingInt(String::length)).get() get the max input
.length() to return the length of the result
Ideone demo
Edit
How I modify the same, to get count to any specific number. I mean, max sequential occurrence of number 4
In this case you can just add a filter .filter(t -> t.matches(number + "+")) which mean get only the numbers which match 4+ where 4 can be any number :
...
int number = 6;
int result = Arrays.asList(arrayTK.replaceAll("(\\d)((?!\\1|$))", "$1;$2").split(";"))
.stream()
.filter(t -> t.matches(number + "+"))
.max(Comparator.comparingInt(String::length)).get().length();
You need something like this:
import java.util.Scanner;
public class A {
public static void main(String[] args) {
Scanner br =new Scanner(System.in);
String str = br.next();
int arr[]=new int[str.length()];
for(int i=0;i<str.length();i++)
{
arr[i]=str.charAt(i)-'0';
//System.out.println(arr[i]);
}
int j=0;
int count=1,max=0;
for(int i=0;i<str.length();i++)
{
if(i==0){
j=arr[i];
}
else
{
if(arr[i]==j)
{
count++;
//System.out.println(" "+count);
}
else
{
if(max<count){
max=count;
}
count=1;
j=arr[i];
}
}
}
if(max<count){
max=count;
}
System.out.println(max);
}
}
That should do the work. Every time you find the matching value you start counting and when the streak is over you compare the length with the maximum length you have found so far.
public int logic(int[] inpArray, int num) {
int count = 0, max = 0
for(int i = 0; i < 10; ++i){
if(inpArray[i] == num) {
count++
else{
if(count > max)
max = count;
count = 0;
}
}
if (count > max)
max = count;
return max;
}