查看: 312| 回复: 0
收起左侧

[Leetcode] min movements to move products

kenpeter | 显示全部楼层
本楼:   👍  0
0%
0%
0   👎
全局:   75
76%
24%
24

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x

这题的答案看不明白。我发了stackoverflow, 但被closed. 希望有人解答一下。


https://stackoverflow.com/questi...nt-to-move-products


Example:
[3_products, 4_products, 6_xxx, 6_xxx, 6_xxx] (index is 1 based; not 0 based)
3 -> 4 -> 6 -> 6 -> 6 (in a cycle)


option 1:
start at index 3th, clockwise
5th -> 1th, cost = 1
4th -> 1th, cost = 2
3rd -> 2nd, cost = 4
each container has 5, total_cost = 1+2+4 = 7


option 2:
start at index 5th, anti-clockwise
3rd -> 1th, cost = 2
4th -> 1th, cost = 3
5th -> 2nd, cost = 3
each container has 5, total_cost = 2+3+3 = 8
7 <= 8, so ans is 7


int getCost(const int n, const vector<int>& a, const int target) {
    int cost = 0, balance = 0, minBalance = 0;
    for (const auto x : a) {
        balance += x - target;
        minBalance = min(minBalance, balance);
        cost += balance;
    }
    return cost - minBalance * n;
}

int solve(vector<int>& a) {
    const int n = (int)a.size(), target = reduce(a.cbegin(), a.cend()) / n;
    const int cw = getCost(n, a, target);
    ranges::reverse(a);
    const int ccw = getCost(n, a, target);
    return min(cw, ccw);
}

int main() {
    vector a {6,6,6,4,3};
    cout << solve(a) << endl; // 7
}






There a few lines which I don't understand:


minBalance = min(minBalance, balance); why do we need to find out the minBalance?


cost += balance; balance1 = point1, balance2 = point1 + point2, balanceN = point1 + ..pointN. Why is this "cost"?


cost - minBalance * n? What is minBalance*n? Why do we take it off from cost?






reference:
https://leetcode.com/discuss/int...new-grad-oa/2648819
https://leetcode.com/discuss/int...zon-OA-question-SDE

上一篇:请教一个算法题
下一篇:在两个排序的list中找全部相同元素
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

Advertisement
>
快速回复 返回顶部 返回列表