Write a function called goodSpread that returns 1
if no value in its array argument occurs more than 3 times in the array.
For example, goodSpread(new int[] {2, 1, 2, 5, 2, 1, 5, 9} returns 1 because no value occurs more than three times.
But goodSpread(new int[ ] {3, 1, 3 ,1, 3, 5, 5, 3} ) returns 0 because the value 3 occurs four times.
If you are writing in Java or C#, the function signature is
int goodSpread (int[ ] a)
If you are writing in C or C++, the function signature is
int goodSpread (int a[ ], int len) where len is the number of elements in the array.
}
For example, goodSpread(new int[] {2, 1, 2, 5, 2, 1, 5, 9} returns 1 because no value occurs more than three times.
But goodSpread(new int[ ] {3, 1, 3 ,1, 3, 5, 5, 3} ) returns 0 because the value 3 occurs four times.
If you are writing in Java or C#, the function signature is
int goodSpread (int[ ] a)
If you are writing in C or C++, the function signature is
int goodSpread (int a[ ], int len) where len is the number of elements in the array.
public static int
goodSpread(int[] a)
{
int[] freq
= new int[a.Length];
int result
= 1;
for (int i = 0; i < a.Length; i++)
{
freq[i] = -1;
}
for (int i = 0; i < a.Length; i++)
{
int count =
1;
for (int j = i + 1; j < a.Length; j++)
{
if (a[i] == a[j])
{
count++;
freq[j] = 0;
}
}
if
(freq[i] != 0)
{
freq[i] = count;
}
}
for (int i = 0; i < freq.Length; i++)
{
if
(freq[i] != 0)
{
if (freq[i] > 3)
{
result = 0;
break;
}
}
}
return result;
}
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
DeleteThis comment has been removed by the author.
ReplyDeleteCan you explain the logic little more
ReplyDelete// O(N^2) Time | O(1) Space
ReplyDeletestatic int goodSpread(int[] arr) {
int result = 0;
for (int i = 0; i < arr.length; i++) {
int count = 0;
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j]) {
count++;
}
}
if (count > 3) {
result = 0;
break;
} else
result = 1;
}
return result;
}
Static int goodSpread(int[]a){
ReplyDeleteint count=0;
for(int i=0;i<a.length;i++){
If(a[i]==a[i+1]{
count+=1;
}
If(count<3){
return 1;
}else
return 0;
}
}
This is the simplest answer :
ReplyDeletepublic class GoodSpread {
public static int goodSpread(int[] a) {
for(int i = 0; i < a.length; i++) {
int count = 0;
for(int j = 0; j < a.length; j++) {
if(a[i] == a[j]) {
count ++;
}
}
if(count >= 3) {
return 0;
}
}
return 1;
}
public static void main(String[] args) {
int[] arr1 = {2, 1, 5, 2, 1, 5, 9};
int[] arr2 = {3, 1, 3, 1, 3, 5, 5, 3};
int result1 = goodSpread(arr1);
int result2 = goodSpread(arr2);
System.out.println("Result 1: " + result1); // 1
System.out.println("Result 2: " + result2); // 0
}
}