DP Algo - Making an array equal by adding to all but one

自古美人都是妖i 提交于 2019-12-13 03:46:47

问题


Was doing a HackerRank problem:

https://www.hackerrank.com/challenges/equal/problem

Where the problem is essentially given an array, find the minimum number of additions it takes to make the array equal by adding to all but one element of the array. Possible values to add are 1, 2, 5.

So if we have an array of [2,2,3,7], we can do:

Choose i = 3 as the excluded element and add all other by 5:
[7,7,8,7]
Choose i = 2 as the excluded and add by 1:
[8,8,8,8] 
This gives minimum of 2 additions.

What I have so far in terms of algorithm is:

I have an Entry object with:

public class entry {
int[] arr;
int count;

public entry(int[] arr, int count) {
    this.arr = arr;
    this.count = count;
    }
}

Because we need to pass in a new copy of the array number of additions (count)

My high-level specification of the algo is:

Entry object e with the given arr and count = 0

int[] poss = {1,2,5};    

static int minOps(entry e, LinkedList<entry> dpMem) {
    int min = Integer.MAX_VALUE;

    if (equal(e.arr)) {
        return e.count;
    }

    int dpCount = checkdpMem(dpMem, e.arr); //checking if already solved

    if (dpCount != -1) { //if solved
        return dpCount;
    } else {
        for (int i = 0; i < poss.length; i++) {
            for (int chosenIndex = 0; chosenIndex < e.arr.length; chosenIndex++) {
                int temp = minOps(increment(e, chosenIndex, poss[i]), dpMem);
                if (temp < min) {
                    min = temp;
                }
            }
        }
    }
    return min;
}

What's happening is it is getting stuck in an infinite loop because it increases all other elements besides the first by 1 continuously. What I need to do is to change the chosen index of exclusion but I'm not sure how to do so in the "proper" way. This is because sometimes you want to keep on increasing in the same "way" multiple times (i.e.: increase everything besides arr[0] by x # of times till they're equal).

Thoughts? Thanks in advance!

来源:https://stackoverflow.com/questions/45665533/dp-algo-making-an-array-equal-by-adding-to-all-but-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!