给定一个整数P ,在接下来的连续N天中,它们分别以50%的概率增加A或B ,任务是在N天后找到期望值。
例子:
Input: P = 1000, A = 5, B = 10, N = 10
Output: 1075
Explanation:
Expected increased value after N consecutive days is equal to:
P + N * (a + b) / 2 = 1000 + 10 × 7.5 = 1000 + 75 = 1075.
Input: P = 2000, a = 10, b = 20, N = 30
Output: 2450
方法:按照以下步骤解决问题:
- 每天的期望增加值=(增加的可能性,A)* A +(增加价值的可能性,B)* B = (1/2)* A +(1/2)* B。
- 因此,一天后的价值增加= (a + b)/ 2。
- 因此, N天后的价值增加= N *(a + b)/ 2。
- 因此, N天后增加的值= P + N *(a + b)/ 2。
- 将增加的值打印为所需的答案。
下面是上述方法的实现:
C++
// C++ program for
// the above approach
#include
using namespace std;
// Function to find the increased
// value of P after N days
void expectedValue(int P, int a,
int b, int N)
{
// Expected value of the
// number P after N days
double expValue
= P + (N * 0.5 * (a + b));
// Print the expected value
cout << expValue;
}
// Driver Code
int main()
{
int P = 3000, a = 20, b = 10, N = 30;
expectedValue(P, a, b, N);
return 0;
}
Java
// Java program for the above approach
class GFG{
// Function to find the increased
// value of P after N days
static void expectedValue(int P, int a,
int b, int N)
{
// Expected value of the
// number P after N days
double expValue = P + (N * 0.5 * (a + b));
// Print the expected value
System.out.print(expValue);
}
// Driver code
public static void main(String[] args)
{
int P = 3000, a = 20, b = 10, N = 30;
expectedValue(P, a, b, N);
}
}
// This code is contributed by abhinavjain194
Python3
# Python3 program for
# the above approach
# Function to find the increased
# value of P after N days
def expectedValue(P, a, b, N):
# Expected value of the
# number P after N days
expValue = P + (N * 0.5 * (a + b))
# Print the expected value
print(int(expValue))
# Driver Code
if __name__ == '__main__':
P = 3000
a = 20
b = 10
N = 30
expectedValue(P, a, b, N)
# This code is contributed by ipg2016107
C#
// C# program for the above approach
using System;
class GFG{
// Function to find the increased
// value of P after N days
static void expectedValue(int P, int a,
int b, int N)
{
// Expected value of the
// number P after N days
double expValue = P + (N * 0.5 * (a + b));
// Print the expected value
Console.Write(expValue);
}
// Driver code
static void Main()
{
int P = 3000, a = 20, b = 10, N = 30;
expectedValue(P, a, b, N);
}
}
// This code is contributed by abhinavjain194
输出:
3450
时间复杂度: O(1)
辅助空间: O(1)