Topic:
Given an array, the number of I represents the price of the day I, please select a strategy to make the most profit. can only buy and sell once a day
Answer:
Find all the rising bands, buy the first day of each interval, sell the last day
input int a[], length
BOOL Haspos = false; Whether there is an open position
for (int i = 0; i < length-1; i++)
{
if (A[i + 1] < A[i])//Tomorrow price falls
{
if (haspos) a[i] = -1;//sell If you have an open position
else a[i] = 0; No position, no movement.
Haspos = false;
}
else if (a[i + 1] > A[i])//Price rises tomorrow
{
if (haspos) a[i] = 0; You can't move with a position.
else a[i] = 1; Buy it without a position.
Haspos = true;
}
else a[i] = 0; The price doesn't change, it doesn't move.
}
A[length-1] = Haspos? -1:0; On the last day, we sell it with open positions.
Get a set of [0, 1, 0, 0,-1, ...] The result of the encounter 1 on the buy, encountered-1 on the Sell
best time to buy and sell stocks