From 78abd1dc3b391fd43caa9c08c31a8cc947c369c1 Mon Sep 17 00:00:00 2001 From: kpeglo Date: Mon, 26 Oct 2026 16:04:43 +0100 Subject: [PATCH] opti n5 --- banque.c | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/banque.c b/banque.c index 23cb7c8..1456418 100644 --- a/banque.c +++ b/banque.c @@ -138,21 +138,32 @@ void total_par_jour(const Transaction *t, int n, long *totaux) /* F5 : période de jours consécutifs dont la somme des soldes est maximale */ long meilleure_periode(const long *totaux, int nb_jours, int *debut, int *fin) { + long P[NB_JOURS + 1]; + long sufmax[NB_JOURS + 1]; + + P[0] = 0; + for (int k = 0; k < nb_jours; k++) + P[k + 1] = P[k] + totaux[k]; + + long min_prefixe = P[0]; long meilleur = totaux[0]; - *debut = 0; - *fin = 0; - for (int i = 0; i < nb_jours; i++) { - for (int j = i; j < nb_jours; j++) { - long somme = 0; - for (int k = i; k <= j; k++) - somme += totaux[k]; - if (somme > meilleur) { - meilleur = somme; - *debut = i; - *fin = j; - } - } + for (int j = 0; j < nb_jours; j++) { + if (P[j] < min_prefixe) min_prefixe = P[j]; + if (P[j + 1] - min_prefixe > meilleur) + meilleur = P[j + 1] - min_prefixe; } + + sufmax[nb_jours - 1] = P[nb_jours]; + for (int i = nb_jours - 2; i >= 0; i--) + sufmax[i] = P[i + 1] > sufmax[i + 1] ? P[i + 1] : sufmax[i + 1]; + + int i = 0; + while (sufmax[i] - P[i] != meilleur) i++; + int j = i; + while (P[j + 1] - P[i] != meilleur) j++; + + *debut = i; + *fin = j; return meilleur; }