The problem is this:
- The array contains N integers.
- The index starts at 0.
- We must split this array into 3 parts at breakpoints P and Q, where:
0 < P < Q < N-1 . - P and Q cannot be adjacent , that is:
QP > 1 . - The cost of this violation is
arr[P]+arr[Q] .
An array can be partitioned in many ways using various legal combinations of P and Q, each of which has its own costs. Find the minimum cost.
For example, an array
arr = [5,2,4,6,3,7]
we can break the following:
P, Q
Therefore, the minimum cost = 5.
My current solution:
public int solution(int[] A) { // code in Java SE 8 int len = A.length; int minCost = A[1]+A[3]; int cost; for(int p=1; p<len-3; p++){ for(int q = p+2; q<len-1; q++){ cost = A[p]+A[q]; if(cost < minCost){ minCost = cost; } } } return minCost; }
As you can see, the time complexity is O (N ^ 2), but for this requirement it is necessary that the solution be O (N). Can you suggest me how I can achieve this.
source share