Skip to content

Commit 41bfc29

Browse files
Create Minimal Cost.java
Hacktoberfest contribution
1 parent 842ff52 commit 41bfc29

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// This is a famoush problem asked in interview rounds.
2+
// It was Asked to me also
3+
4+
Ques:
5+
There is an array arr of heights of stone and Geek is standing at the first stone and can jump to one of the following: Stone i+1, i+2, ... i+k stone, where k is the maximum number of steps that can be jumped and cost will be |hi-hj| is incurred, where j is the stone to land on. Find the minimum possible total cost incurred before the Geek reaches the last stone.
6+
7+
Example:
8+
9+
Input: k = 3, arr[]= [10, 30, 40, 50, 20]
10+
Output: 30
11+
Explanation: Geek will follow the path 1->2->5, the total cost would be | 10-30| + |30-20| = 30, which is minimum
12+
Input: k = 1, arr[]= [10, 20, 10]
13+
Output: 20
14+
Explanation: Geek will follow the path 1->2->3, the total cost would be |10 - 20| + |20 - 10| = 20.
15+
Expected Time Complexity: O(n*k)
16+
Expected Auxilary Space: O(n)
17+
18+
Constraint:
19+
1<= arr.size() <=104
20+
1 <= k <= 100
21+
1 <= arr[i] <= 104
22+
23+
//I have written this solution acc to given contraintand tried to make it as short as possible for easy to understand
24+
CODE:
25+
public int minimizeCost(int k, int arr[]) {
26+
// code here
27+
int[] dp = new int[arr.length];
28+
Arrays.fill(dp,Integer.MAX_VALUE);
29+
dp[0] = 0;
30+
31+
for(int i=0; i<arr.length; i++) {
32+
for(int j=1;j<=k && i+j<arr.length; j++) {
33+
34+
dp[i+j] = Math.min(dp[i+j], dp[i] + Math.abs(arr[i]-arr[i+j]));
35+
}
36+
}
37+
38+
return dp[arr.length-1];
39+
}

0 commit comments

Comments
 (0)