-
Notifications
You must be signed in to change notification settings - Fork 0
/
gasstation.c
98 lines (95 loc) · 2.31 KB
/
gasstation.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include<stdlib.h>
#include<string.h>
#include <stdio.h>
int canCompleteCircuit(int* gas, int gasSize, int* cost, int costSize){
if (gasSize != costSize) return -1;
if (gasSize == 1)
{
if (*gas >= *cost)
{
return 0;
}
else
{
return -1;
}
}
int loopcount = 0;
int startstation = 0;
int i = 0;
int endstation = gasSize - 1;
int succeed = 1;
int gasval = *(gas);
int j = 0;
/* loop through the array */
while(startstation <= gasSize-1)
{
if (startstation == 0)
{
endstation = gasSize - 1;
}
/* we have started in the middle */
else
{
endstation = startstation - 1;
}
//printf("\nstartstation=%d, end station=%d",startstation, endstation);
gasval = *(gas+startstation);
succeed = 1;
for (i = startstation; i != endstation;)
{
// printf("\ni=%d,gasval=%d,cost=%d",i,gasval,*(cost+i));
if (gasval >= *(cost+i))
{
if (i == (gasSize - 1))
{
j = 0;
}
else
{
j = i+1;
}
gasval = (gasval) - (*(cost+i)) + (*(gas+j));
// printf("\nj=%d,newgasval=%d, newgasadded=%d",j,gasval,*(gas+j));
if (i == (gasSize - 1))
{
i = 0;
}
else
{
i++;
}
}
else
{
succeed = 0;
break; // for loop
}
}
// printf("\nsucceed=%d", succeed);
if (succeed == 1)
{
/* check the last station */
// printf("\n11i=%d,gasval=%d,cost=%d",i,gasval,*(cost+i));
if (gasval >= *(cost+i))
{
return startstation;
}
else
{
return -1;
}
}
else
{
startstation++;
}
}
return -1;
}
void main()
{
int gas[]={5,1,2,3,4};
int cost[]={4,4,1,5,1};
printf("\nret=%d\n",canCompleteCircuit((int*)&gas, 5, (int*)&cost, 5));
}