<p>Suppose LeetCode will start its <strong>IPO</strong> soon. In order to sell a good price of its shares to Venture Capital, LeetCode would like to work on some projects to increase its capital before the <strong>IPO</strong>. Since it has limited resources, it can only finish at most <code>k</code> distinct projects before the <strong>IPO</strong>. Help LeetCode design the best way to maximize its total capital after finishing at most <code>k</code> distinct projects.</p>

<p>You are given <code>n</code> projects where the <code>i<sup>th</sup></code> project has a pure profit <code>profits[i]</code> and a minimum capital of <code>capital[i]</code> is needed to start it.</p>

<p>Initially, you have <code>w</code> capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.</p>

<p>Pick a list of <strong>at most</strong> <code>k</code> distinct projects from given projects to <strong>maximize your final capital</strong>, and return <em>the final maximized capital</em>.</p>

<p>The answer is guaranteed to fit in a 32-bit signed integer.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> k = 2, w = 0, profits = [1,2,3], capital = [0,1,1]
<strong>Output:</strong> 4
<strong>Explanation:</strong> Since your initial capital is 0, you can only start the project indexed 0.
After finishing it you will obtain profit 1 and your capital becomes 1.
With capital 1, you can either start the project indexed 1 or the project indexed 2.
Since you can choose at most 2 projects, you need to finish the project indexed 2 to get the maximum capital.
Therefore, output the final maximized capital, which is 0 + 1 + 3 = 4.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> k = 3, w = 0, profits = [1,2,3], capital = [0,1,2]
<strong>Output:</strong> 6
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= k &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= w &lt;= 10<sup>9</sup></code></li>
	<li><code>n == profits.length</code></li>
	<li><code>n == capital.length</code></li>
	<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= profits[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= capital[i] &lt;= 10<sup>9</sup></code></li>
</ul>

// #define MY_DBG

class Solution {
public:
    struct Project {
        int capital = 0;
        int profit = 0;
    };

    struct Chunk {
        int minCapital = 0;
        // sorted by profit ascending. 
        vector<Project> projects;
    };

    int findMaximizedCapital(int k, int w, vector<int>& profits, vector<int>& capital) {
        const size_t n = profits.size();
        const size_t chunkSize = (size_t) sqrt(n) + 1;

        vector<Project> projects(n);
        for (size_t i = 0; i < n; ++i) {
            projects[i].capital = capital[i];
            projects[i].profit = profits[i];
        }
        sort(projects.begin(), projects.end(), [](auto one, auto two) {
            return one.capital > two.capital;
        });

        vector<Chunk> projectByCapitalRanges;
        // splitting into chunks.
        for (size_t i = 0; i < projects.size(); i += chunkSize) {
            size_t end = min(i + chunkSize, projects.size());
            Chunk chunk;
            chunk.projects.assign(projects.begin() + i, projects.begin() + end);
            chunk.minCapital = chunk.projects.back().capital;
            sort(chunk.projects.begin(), chunk.projects.end(), [](auto one, auto two) {
                return one.profit < two.profit;
            });

#ifdef MY_DBG
            cout<<"chunk "<<projectByCapitalRanges.size()<<". minCapital "<<chunk.minCapital<<". [";
            for (const auto& v: chunk.projects)
                cout<<"("<<v.capital<<", "<<v.profit<<") ";
            cout<<"]"<<endl;
#endif

            projectByCapitalRanges.push_back(std::move(chunk));
        }

        // choosing projects.
        for (int i = 0; i < k; ++i) {
            auto it = lower_bound(
                projectByCapitalRanges.begin(), projectByCapitalRanges.end(), w,
                [](const Chunk& chunk, int w) {
                    return chunk.minCapital > w;
                });

#ifdef MY_DBG
            cout<<"mark1. w "<<w<<". "<<distance(projectByCapitalRanges.begin(), it)<<endl;
#endif

            ssize_t projectChunkIdx = -1;
            ssize_t projectIdx = -1;
            
            // have to use linear search for the fist chunk.
            if (it != projectByCapitalRanges.end()) {
                // using linear search in the partially matched chunk
                for (auto i = it->projects.rbegin(); i != it->projects.rend(); ++i) {
                    if (i->capital <= w) {
                        projectChunkIdx = distance(projectByCapitalRanges.begin(), it);
                        projectIdx = it->projects.size() - 1 - 
                            distance(it->projects.rbegin(), i);
                        break;
                    }
                }
                ++it;
            }

#ifdef MY_DBG
            cout<<"mark2"<<endl;
#endif

            // Iterating remaining ranges and trying the most profitable project.
            for (; it != projectByCapitalRanges.end(); ++it) {
                if (projectIdx == -1 || !it->projects.empty() &&
                    it->projects.back().profit > 
                        projectByCapitalRanges[projectChunkIdx].projects[projectIdx].profit
                ) {
                    projectChunkIdx = distance(projectByCapitalRanges.begin(), it);
                    projectIdx = it->projects.size() - 1;
                }
            }

#ifdef MY_DBG
            cout<<"mark3. "<<projectChunkIdx<<", "<<projectIdx<<endl;
#endif

            if (projectIdx == -1)
                break; // did not choose anything. 

            // removing the chosen project.
            w += projectByCapitalRanges[projectChunkIdx].projects[projectIdx].profit;
            projectByCapitalRanges[projectChunkIdx].projects.erase(
                projectByCapitalRanges[projectChunkIdx].projects.begin() + projectIdx);
            
#ifdef MY_DBG
            cout<<"mark4. w = "<<w<<endl;
#endif
        }

        return w;
    }
};
83112