1;问题描述 每日股票都有波动,假设能未卜先知,请问,哪天买入,哪天卖出,利益最大化。(下面只求解了利益最大化的值,若想知道哪天买入,哪天卖出,即下标,请留下评论,本人将用返回结构体地址解决此问题)
int sz[16] = { 13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};//每天的涨跌状态。
2;问题分析,该问题的规模是n,将其分解,为right(n/2),left(n/2)centre(n){centre的规模还是n,但是加了限制条件,必须经过中心点}
3;代码附上。
#define _CRT_SECURE_NO_WARNINGS
#include<math.h>
#include<stdio.h>
int divide(int* p, int left, int right);
int centre(int* p, int left,int mid, int right);
int main()
{
int p;
int sz[16] = { 13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
p=divide(sz, 0, 15);
printf("%d", p);
return 0;
}
int divide(int p[4], int left, int right)
{
if (left == right) return p[left];
int mid = (right + left) / 2;
int l =divide(p, left, mid);//左半边
int r =divide(p, mid+1, right);//右半边
int c=centre(p, left,mid, right);//跨越中间
int max = l > r ? l : r;
max = max > c ? max : c;//找出最大值
#include<math.h>
#include<stdio.h>
int divide(int* p, int left, int right);
int centre(int* p, int left,int mid, int right);
int main()
{
int p;
int sz[16] = { 13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
p=divide(sz, 0, 15);
printf("%d", p);
return 0;
}
int divide(int p[4], int left, int right)
{
if (left == right) return p[left];
int mid = (right + left) / 2;
int l =divide(p, left, mid);//左半边
int r =divide(p, mid+1, right);//右半边
int c=centre(p, left,mid, right);//跨越中间
int max = l > r ? l : r;
max = max > c ? max : c;//找出最大值
return max;
}
int centre(int p[4], int left,int mid, int right)
{
int r_sum=0, r_max=~(((unsigned)-1)>>1), r_sub;
int l_sum=0, l_max=~(((unsigned)-1) >> 1), l_sub;
for (int i = mid; i >= left; i--) {
l_sum += p[i];
l_sum > l_max ? l_max = l_sum : l_max;
}
for (int i = mid+1; i <= right; i++) {
r_sum += p[i];
r_sum > r_max ? r_max = r_sum : r_max;
}
return l_max + r_max;
}
}
int centre(int p[4], int left,int mid, int right)
{
int r_sum=0, r_max=~(((unsigned)-1)>>1), r_sub;
int l_sum=0, l_max=~(((unsigned)-1) >> 1), l_sub;
for (int i = mid; i >= left; i--) {
l_sum += p[i];
l_sum > l_max ? l_max = l_sum : l_max;
}
for (int i = mid+1; i <= right; i++) {
r_sum += p[i];
r_sum > r_max ? r_max = r_sum : r_max;
}
return l_max + r_max;
}