Magical Tree

The little Monk loves to play with strings. One day he was going to a forest. On the way to the forest, he saw a Big Tree(The magical tree of the forest). The magic of the tree was that every leaf of the tree was in the format of string(having some value). Monk wants to have these types of leaves. But he can take only one. Help Monk to choose the most valuable leaf.

Format of the leaf:

a+b+c-d+c+d-x-y+x........, i.e. it contains a string holding a mathematical expression, and the value of that expression will be the value of that particular leaf.

Example:

Input:  L = 4, str ={"8-6+2+4+3-6+1", "1+1+1+1", "2+3+6+8-9", "2+7+1-6"}
Output: 10

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int magicalTree(int Lvector<string&str)
{
    int res = 0max1 = INT_MIN;
    for (int i = 0i < Li++)
    {
        string s = str[i];
        res = 0;
        int n = s.size();
        int x = s[0] - '0'y = s[2] - '0';

        if (s[1] == '-')
            res = x - y;
        else
            res = x + y;

        for (int i = 3i < ni += 2)
        {
            if (s[i] == '-')
                res = res - (s[i + 1] - '0');
            else
                res = res + s[i + 1] - '0';
        }

        max1 = max(max1res);
    }
    return max1;
}
int main()
{
    int L = 4;

    vector<stringstr = {"8-6+2+4+3-6+1""1+1+1+1",
                          "2+3+6+8-9""2+7+1-6"};

    cout << magicalTree(Lstr<< "\n";

    return 0;
}


No comments:

Post a Comment