为什么这种贪心算法有效?
Why does this greedy algorithm work?
这是问题所在:
Given a sequence s of + and - characters which represent +1 and -1 operations respectively on a variable x with initial value 0, find the maximum range of values x can achieve with any subsequence of s.
示例:
s = +--+--+, x = 0
Subsequence that would lead to the maximum range of 4 is +----+. x would have max value 1 and min value -3.
该算法的伪代码解如下:
count_minus = #occurrences of - character
count_plus = #occurences of + character
return max(count_minus, count_plus)
为什么这样做有效?
如果删除所有正数,则 max=0
和 min=-#negatives
对应 range=#negatives
。同样用于去除底片。真的不能再好了。
这是问题所在:
Given a sequence s of + and - characters which represent +1 and -1 operations respectively on a variable x with initial value 0, find the maximum range of values x can achieve with any subsequence of s.
示例:
s = +--+--+, x = 0
Subsequence that would lead to the maximum range of 4 is +----+. x would have max value 1 and min value -3.
该算法的伪代码解如下:
count_minus = #occurrences of - character
count_plus = #occurences of + character
return max(count_minus, count_plus)
为什么这样做有效?
如果删除所有正数,则 max=0
和 min=-#negatives
对应 range=#negatives
。同样用于去除底片。真的不能再好了。