Message from C, C++ talks

June 2019

— Unless you post your code here and we’ll help

— Ok wait

— This is the problem https://www.hackerrank.com/challenges/poisonous-plants/problem

— I'm posting my code

— 

#include <bits/stdc++.h>

using namespace std;

vector<string> split_string(string);

// Complete the poisonousPlants function below.
int poisonousPlants(vector<int> p) {
 long long int a = p.size();
  long long int ci;
  long long int count = 0;
  while (1) {
    ci = 0;
    for (long long int j = p.size() - 1; j > 0; j--) {
      if (p[j] > p[j - 1]) {
        p.erase(p.begin() + j);
        ci++;
      }
    }
    if (ci == 0)
      break;

    count++;
  }
  return count;
}

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    int n;
    cin >> n;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    string p_temp_temp;
    getline(cin, p_temp_temp);

    vector<string> p_temp = split_string(p_temp_temp);

    vector<int> p(n);

    for (int i = 0; i < n; i++) {
        int p_item = stoi(p_temp[i]);

        p[i] = p_item;
    }

    int result = poisonousPlants(p);

    fout << result << "\n";

    fout.close();

    return 0;
}

vector<string> split_string(string input_string) {
    string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
        return x == y and x == ' ';
    });

    input_string.erase(new_end, input_string.end());

    while (input_string[input_string.length() - 1] == ' ') {
        input_string.pop_back();
    }

    vector<string> splits;
    char delimiter = ' ';

    size_t i = 0;
    size_t pos = input_string.find(delimiter);

    while (pos != string::npos) {
        splits.push_back(input_string.substr(i, pos - i));

        i = pos + 1;
        pos = input_string.find(delimiter, i);
    }

    splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));

    return splits;
}

— I'm a noob😅

— So, in array of numbers we need to find in how many iterations we need to do in order to remove any values that are bigger that their previous neighbor, with the given algorithm.

So my thought, that this can be calculated with one iteration over the list. remembering the previous value and trying to eliminate all ascending values after it, and remembering the max step needed to eliminate any ascending values after this specific value.

Message permanent page

— Not sure though

— I can solve this using python

— Using linkedlist in python?

— No

— I didn't got what you said😅.

— Then?

— It can be solved just by using array indexing and deleting

— How can it be solved in one iteration