c++ - 根据给定标准的最大总和

标签 c++ algorithm dynamic-programming

我正在解决作为作业给我的一个问题。我努力尝试但无法达到最佳解决方案。

There are N shops, all aligned linearly having index 1,2,3...N. Buying any positive number of items from a shop S(i) gives a happiness equal to H(i) . Unfortunately due to some unavoidable circumstances, every shop owner has introduced a value L(i). You are credited H(i) happiness from the ith shop if and only if this is the first shop you are buying something from or you buy at least one item from this shop and the last shop you shopped from was S(j) such that L(j)≤L(i) and j<i. Find the maximum sum of happiness that can be obtained following the rules given above!

我想在保留 L(i) 的同时应用最大子数组和作为标准。这是代码->>

long long ans=INT_MIN, temp=0, prev=-1;

for(int i=0;i<n;i++){
    l = L[i];
    if(l>=prev){
        temp+=H[i];
        if(temp<0){
            temp = 0;
            prev = -1;
        }
        if(temp>ans){
            ans = temp;
            prev=L[i];
        }
    }
    else{
        if(H[i]>ans){
            ans = H[i];
            prev = L[i];
            temp = H[i];
        }
        else if(H[i] == ans && L[i]<prev)
            prev = L[i];
    }

这对很多测试用例都不起作用!有更好的解决方案吗?

最佳答案

令 F[i] 等于最后一次访问的商店是 i 时可获得的最大幸福度。

您可以通过计算所有有效前驱(j < i 且 L[j] <= L[i])的最大值,根据先前值 F[j] 计算 F[i]。

那么你能做的最好的就是F[i]中的最大值。

关于c++ - 根据给定标准的最大总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37491174/

相关文章:

c++ - 比较从函数返回的两个 std::string 常量(两个 json-spirit get_str()s)1-liner

algorithm - 为以下难题提出一个算法!

algorithm - 有多少个长度为 n 的单词最多有 k 个连续的元音?

java - 这个算法使用DP吗?

java - 需要帮助理解三步动态编程/递归问题

c++ - 如何读取 PCIe 总线上使用的带宽?

c++ - C++的哨兵while循环

c++ - “SHGFP_TYPE_CURRENT”未在此范围内声明

arrays - 如何在线性时间内按升序查找 3 个数字并在数组中增加索引

algorithm - 支持基于范围的最常出现元素查询的数据结构