Max Sum Of Integers - c++

EDIT: solved! I was treating negative numbers test case as 0, instead of having the output be negative as well. thanks for the help!
Here is the challenge description: https://www.codeeval.com/open_challenges/17/
I keep getting a partially solved score. I want to know why. As in my eyes, this code works. And I believe that it is O(N) time. Thanks for looking!
Here is my code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int max(int a, int b)
{
if (a > b)
return a;
else return b;
}
int maxSubArray(vector<int> values)
{
int max_so_far = values[0];
int curr_max = values[0];
for(int i = 1; i < values.size(); ++i)
{
curr_max = max(values[i], curr_max + values[i]);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
}
int main(int argc, char *argv[])
{
std::vector<vector<int> > Values; //to hold the values of the stock price change
ifstream file(argv[1]);
std::string line; //for the txt file input
int value = 0; //for holding the value of stock change
while (std::getline(file, line))
{
int pos = 0;
if(line.length() == 0)
continue;
else
{
std::istringstream iss(line);
std::vector<int> list; // temporary list of values to be pushed back into the 2-d vector
while (iss >> value)
{
list.push_back(value);
}
Values.push_back(list);
}
}
for(int i = 0; i < Values.size(); ++i)
{
cout << maxSubArray(Values[i]);
cout << endl;
}
/*
cout << " Printing the values : " << endl;
for (int j = 0; j < Values.size(); ++j)
{
for (int k = 0; k < Values[j].size(); ++k)
cout << Values[j][k] << " ";
cout << endl;
}
*/
return 0;
}

so I swapped out some code now. I get better score but I it's still a partial.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <vector>
using namespace std;
int max(int a, int b)
{
if (a > b)
return a;
else return b;
}
int maxSubArray(vector<int> values)
{
int max_so_far = values[0];
int curr_max = values[0];
if (curr_max < 0)
{
curr_max = 0;
max_so_far = 0;
}
for(int i = 1; i < values.size(); ++i)
{
curr_max = max(values[i], curr_max + values[i]);
curr_max = max(curr_max, 0);
max_so_far = max(max_so_far, curr_max);
}
return max_so_far;
}
int main(int argc, char *argv[])
{
std::vector<vector<int> > Values; //to hold the values of the stock price change
ifstream file(argv[1]);
std::string line; //for the txt file input
std::string token; //for the subtring that will be converted from char to int
int value = 0; //for holding the value of stock change
int count = 0;// for holding how many total cases
while (!file.eof())
{
int pos = 0;
getline(file, line);
if(line.length() == 0)
continue;
else
{
std::vector<int> list; // temporary list of values to be pushed back into the 2-d vector
while ((pos = line.find(",")) != std::string::npos )
{
token = line.substr(0,pos);
value = atoi(token.c_str());
line.erase(0, pos + 1);
list.push_back(value);
}
value = atoi(line.c_str());
list.push_back(value);
Values.push_back(list);
++count;
}
}
for(int i = 0; i < Values.size(); ++i)
{
cout << maxSubArray(Values[i]);
cout << endl;
}
cout << " Printing the values : " << endl;
for (int j = 0; j < Values.size(); ++j)
{
for (int k = 0; k < Values[j].size(); ++k)
cout << Values[j][k] << " ";
cout << endl;
}
return 0;
}

Why are you passing the vector by value here?
int maxSubArray(vector<int> values)
That looks like a significant optimization opportunity.
I think you don't read the problem exactly right. When they say 'all contiguous sub ararys', they mean you have to take the max over all i andj of for(idx = i; i < j; ++i) { total += vec[idx]; }. Right now your code basically assumes i = 0 which isn't what you are supposed to do.
Just from looking at the output examples they provide, I can see that your code isn't going to give the answer that they expect.

it seems right, the only thing I can think of is that when the list gets long, your result can overflow, so change int to long long.

Besides technical optimizations suggested in other answers, concerning the algorithm, i think a little fix can make your algorithm work. When curr_max drops to a negative value, due to encountering a negative integer that exceeds curr_max, you can simply drop all the previous integers including the current value and start over. This fix is simple, you can add one line to your loop like this:
for(int i = 1; i < values.size(); ++i)
{
curr_max = max(values[i], curr_max + values[i]);
curr_max = max(curr_max, 0); // <---------------- add this line
max_so_far = max(max_so_far, curr_max);
}

Related

Why is my loop not returning the right answer?

I can't figure it out. What is wrong with my code? I am new to programming.
Program required output: Write a C++ program to find the maximum-occurring character in an array, using a loop.
My code:
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
index = Word[i];
}
}
cout << index << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,100);
FindMaxChar(Word);
}
My Output:
Enter the Word = caaar
r is repeating 11 times.
You never reset count each loop. So you continue incrementing it but never clear it.
Add count = 0 to the beginning of the outer for loop:
for (int i = 0; i < length; i++)
{
count = 0; // Reset counter
You're also trying to use index for two different purposes. You're both using it to store the current character you're looking at (not an index, kind of confusing that you named it like that), AND the character you've seen the most (still not an index, also confusing).
Instead, you need another variable here.
Also note that if you declare Word as char Word[100], it can only hold a c-string of length 99 (to leave room for the null character). So your cin should actually be:
cin.get(Word, 99);
Thanks to the great people of this community.
I am able to find my error and corrected it.
Correct Code :
#include <iostream>
#include <string.h>
using namespace std;
void FindMaxChar(char Word[])
{
int count = 0;
int max = 0;
char index = 0;
char final = 0;
int length = strlen(Word);
for (int i = 0; i < length; i++)
{
index = Word[i];
count = 0;
for (int j = 0; j < length; j++)
{
if (index == Word[j])
{
count++;
}
}
if (count > max)
{
max = count;
final = index;
}
}
cout << final << " is repeating " << max << " times.";
}
int main()
{
char Word[100] = {0};
cout << "Enter the Word = ";
cin.get(Word,99);
FindMaxChar(Word);
}

How can I compare the elements in a vector?

I took a look online and none of the answers solves the problem I have comparing the elements from a vector.
I tried implementing a bool function but the problem is the same.
I am pretty new in c++ so please be patient!
PART2: First of all thank you.
So I changed my programm and created a bool function, the problem is now that it doesn get recognised before 5-6 tries.
#include <iostream>
#include <vector>
#include <time.h>
#include <stdlib.h>
#include <string>
using namespace std;
vector<int> input, compareMe, randomNumbers;
const unsigned int MAX_VEKTORSTELLEN = 5;
const unsigned int UPPER_GRENZE = 49;
const unsigned int LOWER_GRENZE = 1;
unsigned int i, j;
string output;
int random, anzahlRichtige, eingabe;
bool isEqual = false;
string lotto(vector<int>)
{
if (input[i] < LOWER_GRENZE || input[i] > UPPER_GRENZE)
{
output = "Die Zahlen muessen zwischen 1 und 49 liegen! \n";
input.pop_back();
}
else if (input.size() != MAX_VEKTORSTELLEN)
output = "Es muessen 6 Zahlen uebergeben werde! \n";
else if (isEqual == true)
output = "Es duerfen keine doppelten Zahlen vorkommen! \n";
else
for (i = 0; i <= MAX_VEKTORSTELLEN; i++)
srand((unsigned)time(NULL) <= UPPER_GRENZE && (unsigned)time(NULL) > 0);
random = rand();
randomNumbers.push_back(random);
return output;
}
bool compare()
{
compareMe = input;
for (i = 0; i < input.size(); i++)
for (j = 0; j < compareMe.size(); j++)
if (compareMe[j] == input[i])
isEqual = true;
return isEqual;
}
int main()
{
cout << "insert 6 numbers: ";
while (cin >> eingabe)
{
input.push_back(eingabe);
lotto(input);
compare();
cout << output;
for (i = 0; i < input.size(); i++) //Debug
cout << input[i] << ", ";
continue;
}
for (i = 0; i < input.size(); i++)
cout << input[i];
system("pause");
return 0;
}
From line 34 to line I didn´t finish to code but doesn´t really matter because I got stuck before.
All your loops in lotto are wrong. You go one past the end of your containers.
for (i = 0; i <= input.size(); i++)
// ^ !!!
It should be <.
You got this right in main.

Classis task for splitting weights into 2 trucks (C++) (Dynamic Programming)

I have a task that by given line of weights of cages and I have to split them into 2 trucks. The split should be done like this that |a - b| to have least value where 'a' is the common weight of the cages in the first truck and 'b' is the common weight of the cages of second truck. My program seems to work but when I upload it to hackerrank abort function is called. So where is my fault? Here is the code:
#include <iostream>
#include <vector>
#include <sstream>
#include <cstring>
using namespace std;
int main()
{
string input;
int k;
while (getline(cin, input))
{
/* splitting the input into integers */
vector<int> v;
istringstream iss(input);
while (iss >> k) v.push_back(k);
/* --- II --- */
unsigned long sum = 0;
unsigned i, j;
for (i = 0; i < v.size(); i++)
sum += v[i];
vector<char> can;
can.push_back(1);
for (i = 1; i <= sum; i++)
can[i] = 0;
for (i = 0; i < v.size(); i++)
{
for (j = sum; j+1 > 0; j--)
{
if (can[j])
{
can[j + v[i]] = 1;
}
}
}
for (i = sum / 2; i > 1; i--)
{
if (can[i])
{
if (i <= sum - i)
{
cout << i << " " << sum - i << endl;
break;
}
else
{
cout << "a should be <= b";
break;
}
}
}
}
return 0;
}
How can this work?
You create an empty vector of char, push one single value into it and that try to assign value passed the first:
...
vector<char> can;
can.push_back(1); // can contains one single value
for (i = 1; i <= sum; i++)
can[i] = 0; // Error "vector subscript out of range" in debug mode
If you do not ask the control of vector subscript you will just invoke undefined behaviour.
But if you just want to expand the vector, you can repeatedly can push_back:
for (i = 1; i <= sum; i++)
can.push_back(0);

display wheter or not an array entered by the user is unique or not

I am new to C++ I am making an array based off of user input and displaying whether the array is unique or not. my initial thought is I have to end up creating another array to store values and then compare the elements. My code compiles without errors but does not do what I want it to do. I can't used advanced methods such as hashmaps or vectors. Any help or insight is greatly appreciated!
#include <iostream>
#include <string>
using namespace std;
int main()
{
int myArray[6];
string name;
int i, k;
int ov = 0;
int newVal = 0;
for (int index = 0; index < 6; index++)
{
cout << "Enter number a number: ";
cin >> myArray[index];
}//end loop for
for (i = 0; i < 6; i++)
{
ov = myArray[i];
}
for (k = i + 1; k < 6; k++)
{
if (ov == myArray[k])
{
newVal = 1;
}
}
if (newVal == 1)
{
cout << "Not all unique";
}
else
{
cout << "All unique";
}
cin.get();
return 0;
}

least number of digits without duplicates

I am a C++ noob. I have a list of numbers that I put into a Vector. All numbers are 9 digit integers and are unique. I want to know what is the least amount of digits (starting from the right) that can be used to uniquily identify each number in the set. right now there are only 6 numbers, but the list could potentially grow into the thousands. I have posted my code thus far (not working.)
EDIT output is the following...
digit is 1
digit is 1
digit is 1
RUN FINISHED; exit value 0; real time: 0ms; user: 0ms; system: 0ms
This is mostly a learning exercise. Please be generous and explicit with your comments and solutions.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector.at(j) % (10^k));
}
sort(newv.begin(), newv.end());
for (int i = 0; i < (newv.size() - 1); i++) {
if (newv.at(i) == newv.at(i + 1)) {
//there is a duplicate for this digit. Set flag.
myflag = true;
}
if (myflag == false) {
numberFound = true;
cout << "digit is " << k << endl;
} else {
k++;
}
}
}
// for (int i = 0; i < myVector.size(); i++) {
// cout << "||" << myVector.at(i) << "||" << endl;
// }
//
// for (int i = 0; i < newv.size(); i++) {
// cout << "---" << newv.at(i) << "---" << endl;
// }
return 0;
}
Check the below code.
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <math.h>
using namespace std;
int main() {
//declare stream variable and load vector with values
ifstream myfile("mydata.txt");
vector<int> myVector;
int num;
while (myfile >> num) {
myVector.push_back(num);
}
//sort and squack if there is a duplicate.
std::sort(myVector.begin(), myVector.end());
for (int i = 0; i < (myVector.size() - 1); i++) {
if (myVector.at(i) == myVector.at(i + 1)) {
printf("There are duplicate student numbers in the file");
exit(EXIT_FAILURE);
}
}
//if it get here, then there are no duplicates of student numbers
vector<int> newv;
int k = 1;
bool numberFound = false;
bool myflag = false;
int p = 1;
while (numberFound == false) {
//loop through original numbers list and add a digit to newv.
newv.clear();
p = p * 10;
for (int j = 0; j < myVector.size(); ++j) {
newv.push_back(myVector[j] % p);
}
sort(newv.begin(), newv.end());
myflag = false;
for (int i = 0; i < (newv.size() - 1); i++) {
if ( newv[i] == newv[i+1]) {
//there is a duplicate for this digit. Set flag.
myflag = true;
break;
}
}
if (myflag == true){
k ++;
}else{
numberFound = true;
cout << "digit is " << k << endl;
break;
}
}
return 0;
}
Sample Input:
123451789
123456687
125456789
123456780
Output:
digit is 4