Maximum Perimeter Triangle

  • + 0 comments

    include

    using namespace std;

    string ltrim(const string &); string rtrim(const string &); vector split(const string &);

    /* * Complete the 'maximumPerimeterTriangle' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts INTEGER_ARRAY sticks as parameter. */

    vector maximumPerimeterTriangle(vector sticks) { int a=-1,b=-1,c=-1; sort(sticks.begin(),sticks.end(),greater()); int n=sticks.size(); for(int i=0;i

       for(int j=i+1;j<n-1;j++){
           for(int k=j+1;k<n;k++){
               int sum=sticks[j]+sticks[k];
               if(sum>sticks[i]){
                   int peri=a+b+c;
                   if(peri==-3)  a=sticks[i],b=sticks[j],c=sticks[k];
                   int nperi=sum+sticks[i];
                   if(nperi>peri){
                       a=sticks[i],b=sticks[j],c=sticks[k];
                   }
                   else if(nperi==peri){
                       if(a<sticks[i]){
                           a=sticks[i],b=sticks[j],c=sticks[k];
                       }
                       else if(a==sticks[i]){
                           if(c<sticks[k]){
                                a=sticks[i],b=sticks[j],c=sticks[k];
                           }
                       }
                   }
    
               }
           }
       }
    

    } if(a!=-1) return {c,b,a}; return {-1}; }

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

    string n_temp;
    getline(cin, n_temp);
    
    int n = stoi(ltrim(rtrim(n_temp)));
    
    string sticks_temp_temp;
    getline(cin, sticks_temp_temp);
    
    vector<string> sticks_temp = split(rtrim(sticks_temp_temp));
    
    vector<int> sticks(n);
    
    for (int i = 0; i < n; i++) {
        int sticks_item = stoi(sticks_temp[i]);
    
        sticks[i] = sticks_item;
    }
    
    vector<int> result = maximumPerimeterTriangle(sticks);
    
    for (size_t i = 0; i < result.size(); i++) {
        fout << result[i];
    
        if (i != result.size() - 1) {
            fout << " ";
        }
    }
    
    fout << "\n";
    
    fout.close();
    
    return 0;
    

    }

    string ltrim(const string &str) { string s(str);

    s.erase(
        s.begin(),
        find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
    );
    
    return s;
    

    }

    string rtrim(const string &str) { string s(str);

    s.erase(
        find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
        s.end()
    );
    
    return s;
    

    }

    vector split(const string &str) { vector tokens;

    string::size_type start = 0;
    string::size_type end = 0;
    
    while ((end = str.find(" ", start)) != string::npos) {
        tokens.push_back(str.substr(start, end - start));
    
        start = end + 1;
    }
    
    tokens.push_back(str.substr(start));
    
    return tokens;
    

    }