为什么这种贪婪算法有效?

时间:2017-10-20 01:40:25

标签: greedy

问题在于:

  

给定一个+和 - 字符的序列,它们分别代表对初始值为0的变量x的+1和-1运算,找到x可以用s的任何子序列实现的最大值范围。

示例:

  

s = + - + - +,x = 0

     

导致最大范围为4的子序列是+ ---- +。 x的最大值为1,最小值为-3。

伪码中此算法的解决方案如下:

count_minus = #occurrences of - character
count_plus = #occurences of + character
return max(count_minus, count_plus)

为什么这样做?

1 个答案:

答案 0 :(得分:0)

如果您删除所有肯定内容,则max=0 min=-#negativesrange=#negatives Function OFFSETRANGE(AREA As Range, Optional STEP As Integer = 1) As Range Dim Counter As Integer: Counter = 2 Dim TempRange As Range, rCell As Range For Each rCell In AREA.Cells If Counter Mod STEP = 0 Then MsgBox ("In loop" & Counter & " " & rCell) If TempRange Is Nothing Then Set TempRange = rCell Else Set TempRange = Union(TempRange, rCell) End If End If Next Set OFFSETRANGE = TempRange End Function 。同样地删除底片。无法真正做到更好。