This is the c# solution for the Hackerrank problem – Manasa and Stones – Hackerrank Challenge – C# Solution.
Source – Ryan Fehr’s repository.
x
70
70
1
/*
2
Problem: https://www.hackerrank.com/challenges/manasa-and-stones/problem
3
C# Language Version: 7.0
4
.Net Framework Version: 4.7
5
Tool Version : Visual Studio Community 2017
6
Thoughts :
7
Basic t
8
I'm putting here a simple solution to understand for case # 1:
9
n = 4
10
a = 10
11
b = 100
12
13
Few things to note:
14
- End sum for last stone is independent of ordering of differences. Combination will matter to produce unique values for
15
last stone
16
- Since we've to get the sum in increasing order so always start with the smaller difference.
17
18
19
The idea is to start with assuming smaller difference for all stones on the treasure trail as below:
20
21
0,10,10,10 ---resulting stone numbers ----> 0,10,20,30
22
23
Now start replacing the bigger number one by one
24
25
0,10,10,100 ---resulting stone numbers-----> 0,10,20,220
26
0,10,100,100 ---resulting stone numbers-----> 0,10,110,210
27
0,100,100,100 ---resulting stone numbers-----> 0,100,200,300
28
29
I implemented the above logic using a simple for loop with special handling for the case when both differences are equal i.e. a == b
30
31
Time Complexity: O(n)
32
Space Complexity: O(1) //no additional space is required.
33
34
*/
35
using System;
36
37
class Solution
38
{
39
static void Stones(int n, int a, int b)
40
{
41
if (a == b)
42
{
43
Console.Write((n - 1) * a);
44
return;
45
}
46
47
if (b < a)
48
{
49
var temp = b;
50
b = a;
51
a = temp;
52
}
53
54
for (int i = 0; i < n; i++)
55
Console.Write((a * (n - 1 - i) + b * i) + " ");
56
}
57
58
static void Main(String[] args)
59
{
60
var testCases = int.Parse(Console.ReadLine());
61
for (int a0 = 0; a0 < testCases; a0++)
62
{
63
var n = int.Parse(Console.ReadLine());
64
var a = int.Parse(Console.ReadLine());
65
var b = int.Parse(Console.ReadLine());
66
Stones(n, a, b);
67
Console.WriteLine();
68
}
69
}
70
}