

import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
     from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
     from tensorflow.keras.optimizers import Adam


class 			A						(							tf.keras.optimizers.schedules.LearningRateSchedule			):







    """simple docstring"""





    def __init__(				self			:	str,lowercase_			:	float,lowercase_			:	Callable,lowercase_			:	int,lowercase_			:	float = 1.0,lowercase_			:	str = None,)->   Tuple:





        '''simple docstring'''







        super().__init__()
        A__   				=       initial_learning_rate
        A__   				=       warmup_steps
        A__   				=       power
        A__   				=       decay_schedule_fn
        A__   				=       name


    def __call__(				self			:	int,lowercase_			:	Tuple		)->   List[Any]:





        '''simple docstring'''







        with tf.name_scope(self.name or 'WarmUp'		) as name:
            # Implements polynomial warmup. i.e., if global_step < warmup_steps, the
            # learning rate will be `global_step/num_warmup_steps * init_lr`.
            A__   				=       tf.cast(__UpperCamelCase,tf.floataa		)
            A__   				=       tf.cast(self.warmup_steps,tf.floataa		)
            A__   				=       global_step_float / warmup_steps_float
            A__   				=       self.initial_learning_rate * tf.math.pow(__UpperCamelCase,self.power		)
            return tf.cond(
                global_step_float < warmup_steps_float,lambda: warmup_learning_rate,lambda: self.decay_schedule_fn(step - self.warmup_steps		),name=__UpperCamelCase,)


    def 						snake_case__					(				self			:	List[Any]		)->   Dict:





        '''simple docstring'''







        return {
            "initial_learning_rate": self.initial_learning_rate,
            "decay_schedule_fn": self.decay_schedule_fn,
            "warmup_steps": self.warmup_steps,
            "power": self.power,
            "name": self.name,
        }




def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     float   ,      SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     int   ,      SCREAMING_SNAKE_CASE__      :     float = 0.0   ,      SCREAMING_SNAKE_CASE__      :     float = 0.9   ,      SCREAMING_SNAKE_CASE__      :     float = 0.999   ,      SCREAMING_SNAKE_CASE__      :     float = 1E-8   ,      SCREAMING_SNAKE_CASE__      :     Optional[float] = None   ,      SCREAMING_SNAKE_CASE__      :     Optional[float] = None   ,      SCREAMING_SNAKE_CASE__      :     float = 0.0   ,      SCREAMING_SNAKE_CASE__      :     float = 1.0   ,      SCREAMING_SNAKE_CASE__      :     Optional[List[str]] = None   ,      )							->				Any:





    '''simple docstring'''






    A__   				=       tf.keras.optimizers.schedules.PolynomialDecay(
        initial_learning_rate=a__   ,      decay_steps=num_train_steps - num_warmup_steps   ,      end_learning_rate=init_lr * min_lr_ratio   ,      power=a__   ,      )
    if num_warmup_steps:
        A__   				=       WarmUp(
            initial_learning_rate=a__   ,      decay_schedule_fn=a__   ,      warmup_steps=a__   ,      )
    if weight_decay_rate > 0.0:
        A__   				=       AdamWeightDecay(
            learning_rate=a__   ,      weight_decay_rate=a__   ,      beta_a=a__   ,      beta_a=a__   ,      epsilon=a__   ,      clipnorm=a__   ,      global_clipnorm=a__   ,      exclude_from_weight_decay=['LayerNorm', 'layer_norm', 'bias']   ,      include_in_weight_decay=a__   ,      )
    else:
        A__   				=       tf.keras.optimizers.Adam(
            learning_rate=a__   ,      beta_a=a__   ,      beta_a=a__   ,      epsilon=a__   ,      clipnorm=a__   ,      global_clipnorm=a__   ,      )
    # We return the optimizer and the LR scheduler in order to better track the
    # evolution of the LR independently of the optimizer.
    return optimizer, lr_schedule


class 			A						(							_lowercase			):







    """simple docstring"""





    def __init__(				self			:	str,lowercase_			:	Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001,lowercase_			:	float = 0.9,lowercase_			:	float = 0.999,lowercase_			:	float = 1E-7,lowercase_			:	bool = False,lowercase_			:	float = 0.0,lowercase_			:	Optional[List[str]] = None,lowercase_			:	Optional[List[str]] = None,lowercase_			:	str = "AdamWeightDecay",**lowercase_			:	Union[str, Any],)->   Optional[int]:





        '''simple docstring'''







        super().__init__(__UpperCamelCase,__UpperCamelCase,__UpperCamelCase,__UpperCamelCase,__UpperCamelCase,__UpperCamelCase,**__UpperCamelCase		)
        A__   				=       weight_decay_rate
        A__   				=       include_in_weight_decay
        A__   				=       exclude_from_weight_decay


    @classmethod
    def 						snake_case__					(				cls			:	Optional[Any],lowercase_			:	Union[str, Any]		)->   List[Any]:





        '''simple docstring'''







        A__   				=       {'WarmUp': WarmUp}
        return super(__UpperCamelCase,cls		).from_config(__UpperCamelCase,custom_objects=__UpperCamelCase		)


    def 						snake_case__					(				self			:	Tuple,lowercase_			:	str,lowercase_			:	Union[str, Any],lowercase_			:	Any		)->   List[str]:





        '''simple docstring'''







        super(__UpperCamelCase,self		)._prepare_local(__UpperCamelCase,__UpperCamelCase,__UpperCamelCase		)
        A__   				=       tf.constant(
            self.weight_decay_rate,name='adam_weight_decay_rate'		)


    def 						snake_case__					(				self			:	List[Any],lowercase_			:	Tuple,lowercase_			:	Dict,lowercase_			:	str		)->   List[str]:





        '''simple docstring'''







        A__   				=       self._do_use_weight_decay(var.name		)
        if do_decay:
            return var.assign_sub(
                learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['weight_decay_rate'],use_locking=self._use_locking,)
        return tf.no_op()


    def 						snake_case__					(				self			:	List[str],lowercase_			:	List[Any],lowercase_			:	List[str]=None,**lowercase_			:	List[Any]		)->   Optional[int]:





        '''simple docstring'''







        A__				,						A__   				=       list(zip(*__UpperCamelCase		)		)
        return super(__UpperCamelCase,self		).apply_gradients(zip(__UpperCamelCase,__UpperCamelCase		),name=__UpperCamelCase,**__UpperCamelCase		)


    def 						snake_case__					(				self			:	Tuple,lowercase_			:	List[Any],lowercase_			:	Optional[Any],lowercase_			:	str		)->   List[str]:





        '''simple docstring'''







        if apply_state is None:
            return self._decayed_lr_t[var_dtype], {}

        A__   				=       apply_state or {}
        A__   				=       apply_state.get((var_device, var_dtype)		)
        if coefficients is None:
            A__   				=       self._fallback_apply_state(__UpperCamelCase,__UpperCamelCase		)
            A__   				=       coefficients

        return coefficients["lr_t"], {"apply_state": apply_state}


    def 						snake_case__					(				self			:	List[str],lowercase_			:	str,lowercase_			:	Tuple,lowercase_			:	Optional[int]=None		)->   Tuple:





        '''simple docstring'''







        A__				,						A__   				=       self._get_lr(var.device,var.dtype.base_dtype,__UpperCamelCase		)
        A__   				=       self._decay_weights_op(__UpperCamelCase,__UpperCamelCase,__UpperCamelCase		)
        with tf.control_dependencies([decay]		):
            return super(__UpperCamelCase,self		)._resource_apply_dense(__UpperCamelCase,__UpperCamelCase,**__UpperCamelCase		)


    def 						snake_case__					(				self			:	Optional[Any],lowercase_			:	int,lowercase_			:	int,lowercase_			:	Optional[int],lowercase_			:	Any=None		)->   int:





        '''simple docstring'''







        A__				,						A__   				=       self._get_lr(var.device,var.dtype.base_dtype,__UpperCamelCase		)
        A__   				=       self._decay_weights_op(__UpperCamelCase,__UpperCamelCase,__UpperCamelCase		)
        with tf.control_dependencies([decay]		):
            return super(__UpperCamelCase,self		)._resource_apply_sparse(__UpperCamelCase,__UpperCamelCase,__UpperCamelCase,**__UpperCamelCase		)


    def 						snake_case__					(				self			:	Any		)->   Tuple:





        '''simple docstring'''







        A__   				=       super().get_config()
        config.update({'weight_decay_rate': self.weight_decay_rate}		)
        return config


    def 						snake_case__					(				self			:	Dict,lowercase_			:	Any		)->   Dict:





        '''simple docstring'''







        if self.weight_decay_rate == 0:
            return False

        if self._include_in_weight_decay:
            for r in self._include_in_weight_decay:
                if re.search(__UpperCamelCase,__UpperCamelCase		) is not None:
                    return True

        if self._exclude_from_weight_decay:
            for r in self._exclude_from_weight_decay:
                if re.search(__UpperCamelCase,__UpperCamelCase		) is not None:
                    return False
        return True




class 			A						(							_lowercase			):







    """simple docstring"""





    def __init__(				self			:	Dict		)->   Optional[Any]:





        '''simple docstring'''







        A__   				=       []
        A__   				=       None


    @property
    def 						snake_case__					(				self			:	int		)->   Dict:





        '''simple docstring'''







        if self._accum_steps is None:
            A__   				=       tf.Variable(
                tf.constant(0,dtype=tf.intaa		),trainable=__UpperCamelCase,synchronization=tf.VariableSynchronization.ON_READ,aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA,)

        return self._accum_steps.value()


    @property
    def 						snake_case__					(				self			:	str		)->   List[str]:





        '''simple docstring'''







        if not self._gradients:
            raise ValueError('The accumulator should be called first to initialize the gradients'		)
        return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]


    def __call__(				self			:	List[str],lowercase_			:	int		)->   Optional[Any]:





        '''simple docstring'''







        if not self._gradients:
            A__   				=       self.step  # Create the step variable.
            self._gradients.extend(
                [
                    tf.Variable(
                        tf.zeros_like(__UpperCamelCase		),trainable=__UpperCamelCase,synchronization=tf.VariableSynchronization.ON_READ,aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA,)
                    if gradient is not None
                    else gradient
                    for gradient in gradients
                ]		)
        if len(__UpperCamelCase		) != len(self._gradients		):
            raise ValueError(F'Expected {len(self._gradients		)} gradients, but got {len(__UpperCamelCase		)}'		)

        for accum_gradient, gradient in zip(self._gradients,__UpperCamelCase		):
            if accum_gradient is not None and gradient is not None:
                accum_gradient.assign_add(__UpperCamelCase		)

        self._accum_steps.assign_add(1		)


    def 						snake_case__					(				self			:	Tuple		)->   Optional[Any]:





        '''simple docstring'''







        if not self._gradients:
            return
        self._accum_steps.assign(0		)
        for gradient in self._gradients:
            if gradient is not None:
                gradient.assign(tf.zeros_like(__UpperCamelCase		)		)




from collections.abc import Sequence
def 						_snake_case(   SCREAMING_SNAKE_CASE__      :     Sequence[int] | None = None				)							->				int:





    '''simple docstring'''






    if nums is None or not nums:
        raise ValueError('Input sequence should not be empty'				)

    A__   				=       nums[0]
    for i in range(1   ,      len(SCREAMING_SNAKE_CASE__				)				):
        A__   				=       nums[i]
        A__   				=       max(SCREAMING_SNAKE_CASE__   ,      ans + num   ,      SCREAMING_SNAKE_CASE__				)

    return ans


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     # Try on a sample input from the user
     lowercase_			=  int(input("Enter number of elements : ").strip())
     lowercase_			=  list(map(int, input("\nEnter the numbers : ").strip().split()))[:n]
     print(max_subsequence_sum(array))

