candy
There are N children standing in a line. Each child is assigned a rating value.
You are giving candies to these children subjected to the following requirements:
Each child must have at least one candy.
Children with a higher rating get more candies than their neighbors.
What is the minimum candies you must give?
public class Solution {
public int candy(int[] ratings) {
int r=0;
if(ratings==null || ratings.length==0)return 0;
int candies[]=new int [ratings.length];
Arrays.fill(candies,1);
for(int i=1;i<candies.length;i++)if(ratings[i]>ratings[i-1])candies[i]=candies[i-1]+1;
for(int i=candies.length-2;i>=0;i--)if(ratings[i]>ratings[i+1])candies[i]=Math.max(candies[i],candies[i+1]+1);
for(int i=0;i<candies.length;i++)r+=candies[i];
return r;
}
}
Gas station
There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
Return the starting gas station’s index if you can travel around the circuit once, otherwise return -1.
Note:
The solution is guaranteed to be unique.
反证法。从i开始,一直走到gas<0为止,这时候处在位置j . 那么对于任意k, i<=k<=j, 从k到j的gas一定<0,因为从i到k的gas >=0, 从i到j的gas<0.
[code]
public class Solution {
public int canCompleteCircuit(int[] gas, int[] cost) {
int n=gas.length;
if(n<=0)return -1;
int start=0, i=start;
boolean finish=false;
while(finish==false)
{
i=start;
int sum=gas[i]-cost[i];
while(sum>=0)
{
if(i==n-1)finish=true;
i=(i+1)%n;
sum+=gas[i]-cost[i];
if(i==start)return start;
}
if(i==n-1)finish=true;
start=i+1;
}
return -1;
}
}