LeetCode 502. IPO 题解

来源:互联网 发布:thinder 交友软件 编辑:程序博客网 时间:2024/06/05 00:30

题目:
Suppose LeetCode will start its IPO 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 IPO. Since it has limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design the best way to maximize its total capital after finishing at most k distinct projects.

You are given several projects. For each project i, it has a pure profit Pi and a minimum capital of Ci is needed to start the corresponding project. Initially, you have W capital. When you finish a project, you will obtain its pure profit and the profit will be added to your total capital.

To sum up, pick a list of at most k distinct projects from given projects to maximize your final capital, and output your final maximized capital

大意:
大意是,你目前有本金W,每个项目成本是Capital,利润是Profits,你最多进行k个项目,求最大利润。

思路:
简单粗暴,定义了新的数组,赋值为0,若赋值-1则代表这个项目被采用过了,赋值为1这代表它的成本小于w可能被采用,当然采用利润最大的。

代码:

int findMaximizedCapital(int k, int W, int* Profits, int ProfitsSize, int* Capital, int CapitalSize) {    int t = 1;    int cap[CapitalSize];    memset(cap,0,sizeof(cap));    if(CapitalSize<k)        k = CapitalSize;    while(t <= k){        int maxp = 0;        for(int i=0,j=0;i<CapitalSize,j<ProfitsSize;i++,j++){            if(Capital[i] <= W && cap[i] != -1){                cap[i] = 1;            }            if(cap[j] == 1 && Profits[j] > maxp){                maxp = Profits[j];            }        }        for(int m=0;m<ProfitsSize;m++){            if(cap[m] == 1 && Profits[m] == maxp && Capital[m] <= W){                cap[m] = -1;                break;            }        }        W += maxp;        t++;    }    return W;}

理想很美好,现实很惨,超时了。
这里写图片描述

看了网上一些结题,需要用到队列或者映射数据结构,唉 实力不够 留着以后解决!
同时也希望大神大佬大牛们指点迷津~

———————–更新一波 解决啦!———————————————–

贴代码

int findMaximizedCapital(int k, int W, int* Profits, int ProfitsSize, int* Capital, int CapitalSize) {    int t = 1;    if(CapitalSize<k)        k = CapitalSize;    while(t <= k){        int maxp = 0;        int maxn = -1;        for(int i=0;i<CapitalSize;i++){            if(Capital[i] <= W &&  Profits[i] > maxp){                maxp = Profits[i];                maxn = i;            }        }        if(maxn >= 0)            Profits[maxn] = -1;        W += maxp;        t++;    }    return W;}

tips:
1.ProfitsSize和CapitalSize一样的 前面有些循环十分多余
2.开数组也是增加时间复杂度
3.c++高效是真的……