The question says that show the highest and lowest number of that sequence and the number of times that they appear. I now i need to show how many numbers this sequence appears,also they need to be lesser than 2000:
#include <iostream>
int main()
{
int v[11], i, b, l;
for (i = 0; i < 11; i++) {
scanf("%d", &v[i]);
}
b = v[0];
for (i = 0; i < 11; i++) {
if (v[i] > b)
b = v[i];
i++;
}
l = v[0];
for (i = 0; i < 11; i++) {
if (v[i] < l)
l = v[i];
i++;
}
printf("%d\n", b);
printf("%d\n", l);
return 0;
}
And see the input and output how should they appear
Input:
20
40
39
120
2
200
2
360
780
7
2
Output:
biggest:780 Shows 1 time(s)
lowest:2 Shows 3 time(s)
Here is the code for the maximum integer. Use similar method for the minimum integer.
#include <iostream>
int main()
{
int v[11]; // gets the input array
for (i = 0; i < 11; i++) {
scanf("%d", &v[i]);
}
int max = 0;
int count = 0;
for (int i = 0; i < 11; i++)
{
if (v[i] > max)
{
max = v[i];
count = 1;
} else if (v[i] == max)
{
count++;
}
}
}
Explanation
The first for loop gets the input from the user. I haven't changed this part of the code.
The second for loop is where the magic happens. First, we define a maximum variable and a count variable. Both variables are set to zero.
As the for loop iterates through the array, we do some if-statements. First, we check whether the current element is greater than our maximum variable. If this is true, we have found a new maximum variable, so we set max = the current element. We also change the value of count to one, because we have found only one instance so far of the new maximum.
We also check if the current element is equal to the maximum. In this case, we have found another instance of the maximum element so we increment count by 1.
These are the only two cases we have to check. It is simple to apply similar logic for the minimum element.
So here's what i did but still doesn't work what could it be:
#include <iostream>
int main()
{
int v[11],i; // gets the input array
for (i = 0; i < 11; i++) {
scanf("%d", &v[i]);
}
int max = 0;
int count = 0;
for (int i = 0; i < 11; i++)
{
if (v[i] > max)
{
max = v[i];
count = 1;
} else if (v[i] == max)
{
count++;
}
}
int min = 0;
for (int i = 0; i < 11; i++)
{
if (v[i] < min)
{
min = v[i];
count = 1;
} else if (v[i] == min)
{
count++;
}
}
printf("%d\n", max);
printf("%d\n", min);
}
Related
I am trying to learn programming and in our school we have exercises which are automatically checked by a bot. The time limit is 1 second and the memory limit is 1024 mb.
I've tried sorting the array in an ascending order and then multiplicating the 2 highest numbers but that was too slow(my sorting algorithm could be slow so if possible suggest a sorting algorithm.)
This is the fastest way that I've been able to do:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int Maksimumas(int n, int X[]);
ofstream fr("U1rez.txt");
ifstream fd("U1.txt");
int main()
{
int n, A[100000], B[100000], maxi=0;
fd >> n;
for (int i = 0; i < n; i++) {
fd >> A[i];
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
B[j] = A[i] * A[j];
}
maxi = Maksimumas(n, B);
A[i] = B[maxi];
}
maxi = Maksimumas(n, A);
fr << A[maxi];
fr.close();
return 0;
}
int Maksimumas(int n, int X[])
{
int maxi = 0;
for (int i = 0; i < n; i++) {
if (X[maxi] < X[i]) {
maxi = i;
}
}
return maxi;
}
n is the size of the array for anyone wondering.
You don't need to sort the entire array - you just need the two largest positive numbers and the two smallest negative numbers. Everything in between is inconsequential.
Instead, you can go over all the input and keep track of the two largest positive numbers and two smallest negative numbers.; At the end of the iteration, multiply each pair (if found), and compare the results.
// fd is opened like the original question, n is the number of elements to read
// that part is omitted for brevity
int max = -1;
int preMax = -1;
int min = 1;
int preMin = 1;
int temp;
for (int i = 0; i < n; i++) {
fd >> temp;
if (temp > preMax) {
if (temp > max) {
preMax = max;
max = temp;
} else {
preMax = temp;
}
} else if (temp < preMin) {
if (temp < min) {
preMin = min;
min = temp;
} else {
preMin = temp;
}
}
}
int result = -1;
if (preMax >= 0) {
result = preMax * max;
}
if (preMin <= 0) {
int tempResult = preMin * min;
if (tempResult > result) {
result = tempResult;
}
}
return result;
I was trying to solve this proble:
A gallery with plants is divided into n parts, numbered : 0,1,2,3...n-1. There are provisions for attaching water sprinklers at every partition. A sprinkler with range x at partition i can water all partitions from i-x to i+x.
Given an array gallery[ ] consisting of n integers, where gallery[i] is the range of sprinkler at partition i (power==-1 indicates no sprinkler attached), return the minimum number of sprinklers that need to be turned on to water the complete gallery.
If there is no possible way to water the full length using the given sprinklers, print -1.
and this is how I ended up trying-
Create a frequency array such that the ith element contains the number of sprinklers that are watering the ith part of the gallery.
If any element of this array is zero after going through all the sprinklers, then return -1 as even if all the sprinklers tried they couldn't water each part.
Then, std::stable_sort all the sprinklers based on their range, in increasing order.
Then, remove a sprinkler if it is redundant, starting from the smallest range to the largest.
My implementation of the same-
typedef struct sprinkler {
int l;
int r;
} sprinkler;
int min_sprinklers(int gallery[], int n)
{
int freq[n];
vector<sprinkler> vec;
for(int i = 0; i < n; i++) freq[i] = 0;
for(int i = 0 ; i < n; i++) {
int x = gallery[i];
if(x == -1) continue;
int l = max(0, i - x);
int r = min(n-1, i + x);
sprinkler s;
s.l = l;
s.r = r;
vec.push_back(s);
for(int j = l; j <= r; j++) {
freq[j]++;
}
}
for(int i = 0; i < n; i++) {
if(freq[i] == 0) return -1;
}
stable_sort(vec.begin(), vec.end(), [](sprinkler s1, sprinkler s2) { return s1.r-s1.l < s2.r-s2.l; });
int sprinklers = vec.size();
for(int i = 0; i < vec.size(); i++) {
int l = vec[i].l;
int r = vec[i].r;
bool flag = false;
for(int j = l; j <= r; j++) {
if(freq[j] == 1) {
flag = true;
break;
}
}
if(!flag) {
for(int j = l; j <= r; j++) freq[j]--;
sprinklers--;
}
}
return sprinklers;
}
But I still seem to be missing something and still don't know what.
Link to try my code:
https://practice.geeksforgeeks.org/problems/410d51d667ab93f2219b15126f001f32e8bb029e/0/?category[]=Greedy&category[]=Greedy&difficulty[]=1&page=1&query=category[]Greedydifficulty[]1page1category[]Greedy#
I'm practicing myself by doing some leetcode questions, however, I don't know why that's an overflow problem right here. I knew the way I sum the subarray was terrible, any tips for the sum of the subarray?
and the run time for this code would be forever
#include <numeric>
class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
int size = arr.size();//5
int ans = 0;
int sumAll = 0;
int start = 3;
int tempsum;
for(int i =0; i< size; i++){ //sumitself
sumAll += arr[i];
}
ans = sumAll; //alreayd have the 1 index
if(size%2 == 0){//even number 6
int temp = size-1; //5
if(size == 2)
ans = sumAll;
else{
while(start <= temp){//3 < 5
for(int i = 0; i< size; i++){
for(int k =0; k< start; k++){//3
tempsum += arr[i+k];
if(i+k > temp) //reach 5
break;
}
}
start+=2;
}
}
ans+= tempsum;
}
else{//odd number
if(size == 1)
ans = sumAll;
else{
while(start < size){//3
for(int i = 0; i< size; i++){
for(int k =0; k< start; k++){//3
tempsum += arr[i+k];
if(i+k > size) //reach 5
break;
}
}
start+=2;
}
ans+= tempsum;
ans+= sumAll; //size index
}
}
return ans;
}
};
The problem is with arr[i+k]. The result of i + k can be equal to, or larger, than size. You check it after you have already gone out of bounds.
You should probably modify the inner loop condition so that never happens:
for(int k =0; k < start && (i + k) < size; k++){//3
Now you don't even need the inner check.
You can use prefix sum array technique and then for each index you can calculate the sub-array sum for each odd-length array using prefix sum array. I submitted the below solution in LeetCode and it beats runtime of 100% of submissions and memory usage of 56.95%
class Solution {
public:
int sumOddLengthSubarrays(vector<int>& arr) {
int n = arr.size();
vector<int> prefix(n+1,0);
int sum = 0;
prefix[1] = arr[0];
for(int i=1;i<n;i++)
prefix[i+1]=(arr[i]+prefix[i]);
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j+=2)
sum+=prefix[j+1]-prefix[i];
}
return sum;
}
};
https://leetcode.com/problems/sum-of-all-odd-length-subarrays/discuss/1263893/Java-100-one-pass-O(n)-with-explanation
class Solution {
public int sumOddLengthSubarrays(int[] arr) {
// alt solution: O(n)
//for each i:
// if(n -1 - i) is odd, then arr[i] is counted (n-1-i)/2 + 1 times, each from 0 to i, total ((n-i)/2+1)*(i+1) times
// if(n -1 - i) is even, then arr[i] is counted (n-1-i)/2 + 1 times, if starting subseq index diff with i is even;
// (n-1-i)/2 times, if starting index diff with i s odd, total (n-i)/2 *(i+1) + (i+1)/2
// if i is even i - 1, i - 3, .. 1, total (i -2)/2 + 1 = i / 2 = (i+1) / 2
// if i is odd i-1, i-3, .., 0 total (i-1)/2 + 1 = (i+1) / 2
int total = 0;
int n = arr.length;
for(int i = 0; i < n; i++)
total += (((n - 1 - i) / 2 + 1) * (i + 1) - ((n-i) % 2)*((i+1) / 2)) * arr[i];
return total;
}
}
This code is supposed to calculate the frequency of maximum number in an array I.E the number of times the highest number in the array has occured unfortunately this code does not display any output:-
#include<iostream>
#include <bits/stdc++.h>
using namespace std;
int birthdayCakeCandles(int n, int a[]){
int j=0,max,count=0;
max = a[j];
while(j<n){
if(a[j+1]> max){
max = a[j+1];
j++;
}
}
int seen[n];
for(int i = 0; i < n; i++)
seen[i] = 0;
for(int i = 0; i < n;i++) {
if(seen[i] == 0) {
int count = 0;
for(int j = i; j < n;j++)
if(a[j] == a[i] && a[i] == max)
count += 1;
seen[j] = 1;
}
}
return count;
}
int main() {
int i,n;
cin >> n;
int a[n];
for(i = 0; i < n; i++){
cin >> a[i];
}
int result = birthdayCakeCandles(n, a);
cout << result << endl;
return 0;
}
Your program never stops, because your maximum finding loop is for n > 0 endless. Your loop in birthdayCakeCandles should be changed to:
while (j < n)
{
if (a[j + 1] > max)
{
max = a[j + 1];
}
j++;
}
Also consider using more readable coding style and please read this.
In addition to the bug found by vasek, you made at least another mistake in the (overcomplicated) following loops, where you are trying to count the occurences of the maximum value.
// I've kept OP's indentation on purpose...
int seen[n]; // <-- Variable Length Arrays are not standard in C++
for(int i = 0; i < n; i++)
seen[i] = 0;
for(int i = 0; i < n;i++) {
if(seen[i] == 0) {
int count = 0;
for(int j = i; j < n;j++)
if(a[j] == a[i] && a[i] == max)
count += 1;
seen[j] = 1; // <-- misleading indentation, this is always executed
// no matter what the condition is
}
}
While all you need to do, once you have found the maximum value, is:
int count = 0;
for( int i = 0; i < n; ++i ) {
if( a[i] == max )
++count;
}
As a matter of fact (unless you want to create a function operating on an array for other reasons), you don't need any array (or std::vector) at all to complete your assignment. This code will perform the same task:
#include <iostream>
#include <limits>
int main()
{
int n;
std::cin >> n;
int x,
max = std::numeric_limits<int>::min();
int count = 0;
for ( int i = 0;
i < n && std::cin >> x;
++i )
{
if ( x >= max )
{
if ( x > max )
{
max = x;
count = 1;
}
else
{
++count;
}
}
}
std::cout << count << '\n';
}
For some reason, this always returns value 1. The point of this is to find the starting number (1-1,000,000) that loops the most amount of times (until j = 1). j will always end up being 1 eventually (collatz theory), I divide j by 2 if it's even, or multiple by 3 and add 1 if it's odd.
#include <iostream>
using namespace std;
int collatz() {
int counter = 0;
int holder = 0;
for (int i = 999999; i > 1; i--){ // loops 999,999 times
for (int j = i; j != 1; counter++) { // loops until j = 1, records amount of loops
if (j % 2 == 0) { // if j is even, divide by 2, +1 to counter
j = j / 2;
} else {
j = (j*3) + 1; // if j is odd, multiply by 3 and add 1, +1 to counter
}
}
if (holder < counter){ // records highest number of loops
holder = counter;
counter = 0;
} else {
counter = 0;
}
}
return holder;
}
int main()
{
cout << collatz << endl;
return 0;
}
You're not calling your function, you're printing out the function pointer (which is converted to the bool value true (i.e. 1)).
First, use unsigned int or unsigned long long as the variable type of j to increase the arithmetic range.
Then, in the loop, check for overflow.
while (j!=1) {
counter++;
if (j % 2 == 0) {
j >>= 1;
} else {
unsigned int j2 = j;
j = (j*3) + 1;
if (j2 > j) {
return -1; // or surround this with try/catch/throw exception
}
}
}
With int i; the counter will overflow at i==113383;
and with unsigned int i; at 159487. If these are not checked, there's a possibility of infinite loop.