how to fix this programme - c++

Given an array A, find the highest unique element in array A. Unique element means that element should present only once in the array.
Input:
First line of input contains N, size of array A. Next line contains N
space separated elements of array A.
Output:
Print highest unique number of array A. If there is no any such
element present in array then print -1.
Constraints:
1 ≤ N ≤ 106 0 ≤ Ai ≤ 109
SAMPLE INPUT
5 9 8 8 9 5
SAMPLE OUTPUT
5
Explanation
In array A: 9 occur two times. 8 occur two times. 5 occur once hence the answer is 5.
Can you explain what is wrong with this code?
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int a[n], i, max = -99;
for (i = 0; i < n; i++) {
cin >> a[i];
}
for (i = 0; i < n; i++) {
if (a[i] > max) {
max = a[i];
cout << max;
}
}
for (i = 0; i < n; i++) {
if (max == a[i]) {
break;
} else {
// cout<<"-1";
}
max =
}
return 0;
}

There's a few problems here (right now it won't even compile at max =). But the algorithmic problem is this: the second for loop finds the maximum before rejecting duplicate entries. The reverse is needed. First reject duplicates (say, by setting them to -99), then find the max of what is left over.

Related

How to match a list of bounds with a list of numbers, one-to-one

The task
I am solving a leetcode style task. Find the amout of values, that can be sortet into a bound (lower <= value <= upper).
Input: first line contains n & m, the amout of bounds and the amount of values.
The second line contains the n lower bounds.
The third line contains the n upper bounds.
The fourth line contains m the values.
(A single bound is li and ri)
Now find the amout of Values, that can be sorted into the bounds, if we do it optimally. (and output it)
Note: Each value can only be assigned one bound and one bound only to one value.
Ex. Input:
3 4
1 7 3
4 9 8
5 2 9 2
outputs 3.
My solution
I have a struct for the bounds:
struct Bounds {
int min, max;
// operator for sorting both primary and secondary keys
bool operator < (const Bounds& rhs) const
{
if ( min == rhs.min )
return max > rhs.max;
else
return min > rhs.min;
}
};
and solve as follows:
int main()
{
int n, m, rval = 0;
cin >> n >> m;
Bounds newBound = {0, 0};
vector<Bounds> bounds(n, newBound);
vector<int> values(m);
// get input
for (int i = 0; i < n; i++)
cin >> bounds[i].min;
for (int i = 0; i < n; i++)
cin >> bounds[i].max;
for (int i = 0; i < m; i++)
cin >> values[i];
// sort Bounds in descending order by lower bound as primary and upper bound as secondary
std::sort(bounds.begin(), bounds.end(), less<Bounds>());
//sort values in ascending order
std::sort(values.begin(), values.end(), greater<int>());
// for every bound
for (int j = 0; j < m; j++) {
int value = values[j];
for (int i = 0; i < bounds.size(); i++)
{
if (bounds[i].min <= value && value <= bounds[i].max) {
rval++;
bounds.erase(bounds.begin() + i);
break;
}
}
}
cout << rval << "\n";
}
My Problem
This works, but:
I don't think this is the optimal solution,
It's to slow, as one Testcase with 10^6 values takes ~7 minutes to solve.
How can I improve it? Or should I scrap this approach?
I think my solution has 0(n^2 + (n log(n)))
Or Phrased differently: How can I remove the nested for loop?

O(n^2) algorithm to find largest 3 integer arithmetic series

The problem is fairly simple. Given an input of N (3 <= N <= 3000) integers, find the largest sum of a 3-integer arithmetic series in the sequence. Eg. (15, 8, 1) is a larger arithmetic series than (12, 7, 2) because 15 + 8 + 1 > 12 + 7 + 2. The integers apart of the largest arithmetic series do NOT have to be adjacent, and the order they appear in is irrelevant.
An example input would be:
6
1 6 11 2 7 12
where the first number is N (in this case, 6) and the second line is the sequence N integers long.
And the output would be the largest sum of any 3-integer arithmetic series. Like so:
21
because 2, 7 and 12 has the largest sum of any 3-integer arithmetic series in the sequence, and 2 + 7 + 12 = 21. It is also guaranteed that a 3-integer arithmetic series exists in the sequence.
EDIT: The numbers that make up the sum (output) have to be an arithmetic series (constant difference) that is 3 integers long. In the case of the sample input, (1 6 11) is a possible arithmetic series, but it is smaller than (2 7 12) because 2 + 7 + 12 > 1 + 6 + 11. Thus 21 would be outputted because it is larger.
Here is my attempt at solving this question in C++:
#include <bits/stdc++.h>
using namespace std;
vector<int> results;
vector<int> middle;
vector<int> diff;
int main(){
int n;
cin >> n;
int sizes[n];
for (int i = 0; i < n; i++){
int size;
cin >> size;
sizes[i] = size;
}
sort(sizes, sizes + n, greater<int>());
for (int i = 0; i < n; i++){
for (int j = i+1; j < n; j++){
int difference = sizes[i] - sizes[j];
diff.insert(diff.end(), difference);
middle.insert(middle.end(), sizes[j]);
}
}
for (size_t i = 0; i < middle.size(); i++){
int difference = middle[i] - diff[i];
for (int j = 0; j < n; j++){
if (sizes[j] == difference) results.insert(results.end(), middle[i]);
}
}
int max = 0;
for (size_t i = 0; i < results.size(); i++) {
if (results[i] > max) max = results[i];
}
int answer = max * 3;
cout << answer;
return 0;
}
My approach was to record what the middle number and the difference was using separate vectors, then loop through the vectors and search if the middle number minus the difference is in the array, where it gets added to another vector. Then the largest middle number is found and multiplied by 3 to get the sum. This approach made my algorithm go from O(n^3) to roughly O(n^2). However, the algorithm doesn't always produce the correct output (and I can't think of a test case where this doesn't work) every time, and since I'm using separate vectors, I get a std::bad_alloc error for large N values because I am probably using too much memory. The time limit in this question is 1.4 sec per test case, and memory limit is 64 MB.
Since N can only be max 3000, O(n^2) is sufficient. So what is an optimal O(n^2) solution (or better) to this problem?
So, a simple solution for this problem is to put all elements into an std::map to count their frequencies, then iterate over the first and second element in the arithmetic progression, then search the map for the third.
Iterating takes O(n^2) and map lookups and find() generally takes O(logn).
include <iostream>
#include <map>
using namespace std;
const int maxn = 3000;
int a[maxn+1];
map<int, int> freq;
int main()
{
int n; cin >> n;
for (int i = 1; i <= n; i++) {cin >> a[i]; freq[a[i]]++;} // inserting frequencies
int maxi = INT_MIN;
for (int i = 1; i <= n-1; i++)
{
for (int j = i+1; j <= n; j++)
{
int first = a[i], sec = a[j]; if (first > sec) {swap(first, sec);} //ensure that first is smaller than sec
int gap = sec - first; //calculating difference
if (gap == 0 && freq[first] >= 3) {maxi = max(maxi, first*3); } //if first = sec then calculate immidiately
else
{
int third1 = first - gap; //else there're two options for the third element
if (freq.find(third1) != freq.end() && gap != 0) {maxi = max(maxi, first + sec + third1); } //finding third element
}
}
}
cout << maxi;
}
Output : 21
Another test :
6
3 4 5 7 7 7
Output : 21
Another test :
5
10 10 9 8 7
Output : 27
You can try std::unordered_map to try and reduce the complexity even more.
Also see Why is "using namespace std;" considered bad practice?
The sum of a 3-element arithmetic progression is 3-times the middle element, so I would search around a middle element, and would start the search from the "upper" end of the "array" (and have it sorted). This way the first hit is the largest one. Also, the actual array would be a frequency-map, so elements are unique, but still track if any element has 3 copies, because that can become a hit (progression by 0).
I think it may be better to create the frequency-map first, and sort it later, simply because it may result in sorting fewer elements - though they are going to be pairs of value and count in this case.
function max3(arr){
let stats=new Map();
for(let value of arr)
stats.set(value,(stats.get(value) || 0)+1);
let array=Array.from(stats); // array of [value,count] arrays
array.sort((x,y)=>y[0]-x[0]); // sort by value, descending
for(let i=0;i<array.length;i++){
let [value,count]=array[i];
if(count>=3)
return 3*value;
for(let j=0;j<i;j++)
if(stats.has(2*value-array[j][0]))
return 3*value;
}
}
console.log(max3([1,6,11,2,7,12])); // original example
console.log(max3([3,4,5,7,7,7])); // an example of 3 identical elements
console.log(max3([10,10,9,8,7])); // an example from another answer
console.log(max3([1,2,11,6,7,12])); // example with non-adjacent elements
console.log(max3([3,7,1,1,1])); // check for finding lowest possible triplet too

C++ Program to print sum of digits

//Program to print sum of digits
#include <iostream>
using namespace std;
int main()
{
int n, m, sum = 0;
cin >> n;
for(int i = 0; i < n; i++)
{
m = n % 10;
sum += m;
n = n / 10;
}
cout << sum;
}
//Outputs
// Input = 123
// Output = 5 (should be 6)
// Input = 0235
// Ouput = 8 (should be 9)
Not printing the right answer when input no. is starting from 1 or 0.
By using While (n>0), it's giving the right output but I can't figure out why?
For starters the user can enter a negative number because the type of the variable n is the signed type int.
Thus neither loop either
for(int i = 0; i < n; i++)
or
while (n>0)
will be correct.
A correct loop can look like
while ( n != 0 )
And you need to convert each obtained digit to a non-negative value or you should use an unsigned integer type for the variable n.
As for this loop
for(int i = 0; i < n; i++)
then it entirely does not make a sense.
For example let's assume that n is initially equal to 123,
In this case the in the first iteration of the loop the condition of the loop will look like
0 < 123
In the second iteration of the loop it will look like
1 < 12
And in the third iteration of the loop it will look like
2 < 1
That means that the third iteration of the loop will not be executed.
Thus as soon as the last digit of a number is less than or equal to the current value of the index i the loop stops its iterations and and the digit will not be processed.

The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence

It's showing the wrong answer. Can anybody please tell me which test case I am missing ?
Without Adjacent
Given an array arr[] of N positive integers. The task is to find a subsequence with maximum sum such that there should be no adjacent elements from the array in the subsequence.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains size of array N. Next line contains N elements of the array space seperated.
Output:
For each testcase, print the maximum sum of the subsequence.
Constraints:
1 <= T <= 100
1 <= N <= 10^6
1 <= arr[i] <= 10^6
Example:
Input:
2
3
1 2 3
3
1 20 3
Output:
4
20
Explanation:
Testcase 1: Elements 1 and 3 form a subsequence with maximum sum and no elements in the subsequence are adjacent in the array.
Testcase 2: Element 20 from the array forms a subsequence with maximum sum.
I tried using below test cases also
Input:
3
9
1 2 9 4 5 0 4 11 6
1
0
1
1
Output:
26
0
1
It worked fine but while submitting it was giving "wrong answer" I don't know for which test case it was talking about
Here is my solution:
#include<iostream>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int sum1,sum2,sum_even=0,sum_odd=0;
for(int i=0;i<n;i+=2)
sum_even+=arr[i];
for(int i=1;i<n;i+=2)
sum_odd+=arr[i];
if(n>=1)
sum1 = arr[0];
else
sum1 = -1;
if(n>=2)
sum2 = arr[1];
else
sum2 = -1;
int new_sum,i;
for(i=2; i<n; i+=2)
{
if((i+1)!=n && arr[i+1]>arr[i])
{
i++;
sum1+=arr[i];
}
else if(i+1==n)
{
sum1+=arr[i];
}
else
{
sum1+=arr[i];
}
}
for(i=3; i<n; i+=2)
{
if((i+1)!=n && arr[i+1]>arr[i])
{
i++;
sum2+=arr[i];
}
else if(i+1 ==n)
{
sum2+=arr[i];
}
else
{
sum2+=arr[i];
}
}
int sum = sum1>sum2 ? sum1 : sum2;
sum = sum>sum_odd ? sum : sum_odd;
sum = sum>sum_even ? sum : sum_even;
cout<<sum<<endl;
}
return 0;
}
The issue is that you seem to made some guesses on the structure on any solution.
Your code is rather complex and it is difficult effectively to find a counter example by hand.
I made a random generation of arrays and compare your result with the optimal one.
I finally obtained this counter example : [14 18 8 19 22 1 20 23]. Your code gives a result of 64, while the optimum sum is equal to 67.
A simple optimum solution is to iteratively calculate two sums, both corresponding to a maximum up to the current index i,
the first sum (sum0) assuming current value arr[i] is not used, the second sum (sum1) assuming the current value arr[i] is used.
#include <iostream>
#include <vector>
#include <algorithm>
int max_sum (const std::vector<int>& arr) {
int sum0 = 0;
int sum1 = arr[0];
int n = arr.size();
for (int i = 1; i < n; ++i) {
int temp = sum0;
sum0 = std::max (sum0, sum1);
sum1 = temp + arr[i];
}
return std::max (sum0, sum1);
}
int main() {
int t;
std::cin >> t;
while(t--) {
int n;
std::cin >> n;
std::vector<int> arr(n);
for(int i = 0; i < n; i++)
std::cin >> arr[i];
int sum = max_sum (arr);
std::cout << sum << '\n';
}
}

c++:Hackerank:Error in taking input

This is a part of my question.I tried many times but couldn't get the answer
Problem Statement
You are given a list of N people who are attending ACM-ICPC World Finals. Each of them are either well versed in a topic or they are not. Find out the maximum number of topics a 2-person team can know. And also find out how many teams can know that maximum number of topics.
Note Suppose a, b, and c are three different people, then (a,b) and (b,c) are counted as two different teams.
Input Format
The first line contains two integers, N and M, separated by a single space, where N represents the number of people, and M represents the number of topics. N lines follow.
Each line contains a binary string of length M. If the ith line's jth character is 1, then the ith person knows the jth topic; otherwise, he doesn't know the topic.
Constraints
2≤N≤500
1≤M≤500
Output Format
On the first line, print the maximum number of topics a 2-person team can know.
On the second line, print the number of 2-person teams that can know the maximum number of topics.
Sample Input
4 5
10101
11100
11010
00101
Sample Output
5
2
Explanation
(1, 3) and (3, 4) know all the 5 topics. So the maximal topics a 2-person team knows is 5, and only 2 teams can achieve this.
this is a a part of my work.Any clue how can i get this to work
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int n, m, max = 0, max1 = 0, count = 0;
cin >> n >> m; //for input of N and M
int a[n][m];
for (int i = 0; i<n; i++) //for input of N integers of digit size M
for (int j = 0; j<m; j + >>
cin >> a[i][j];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
max = 0;
for (int k = 0; k<m; k++)
{
if (a[i][k] == 1 || a[j][k] == 1) max++;
cout << k;
if (k = m - 1 && max>max1) max1 = max;
if (k == m - 1 && max == max1) count++;;
}
}
}
cout << max1 << endl << count;
return 0;
}
I think the way of taking my input logic is wrong.could you please help me out.I am stuck in this question from 5 days.
PLease only help me on how should i take input and how to read the digit of integer.
Don't have a compiler with me so there's probably a syntax boner or two in there, but the logic walks through on paper.
Builds the storage:
std::cin >> n >> m; //for input of N and M
std::vector<std::vector<bool>>list(n,std::vector<bool>(m, false));
Loads the storage:
char temp;
for (int i = 0; i < n; i++) //for input of N integers of digit size M
{
for (int j = 0; j < m; j++)
{
std::cin >> temp;
if (temp == 1)
{
list[i][j] = true;
}
}
}
Runs the algorithm
for (int a = 0; a < n; a++)
{
for (int b = a+1; b < n; b++)
{
int knowcount = 0;
for (int j = 0; j < m; j++)
{
if (list[a][j] | list[b][j])
{
knowcount ++;
}
}
if (knowcount > max)
{
groupcount = 1;
max = know;
}
else if(knowcount == max)
{
groupcount ++;
}
}
}
Your method of input is wrong. According to your method, the input will have to be given like this (with spaces between individual numbers):
1 0 1 0 1
1 1 1 0 0
1 1 0 1 0
0 0 1 0 1
Only then it makes sense to create a matrix. But since the format in the question does not contain any space between a number in the same row, thus this method will fail. Taking into consideration the test case, you might be tempted to store the 'N' numbers in a single dimensional integer array, but keep in mind the constraints ('M' can be as big as 500 and int or even unsigned long long int data type cannot store such a big number).