{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Leaders\n", "An element is leader if it is greater than all the elements to its right side. And the rightmost element is always a leader.\n", "For example in the array [16, 17, 4, 3, 5, 2], leaders are 17, 5 and 2." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def getLeaders(arr):\n", " big = arr[len(arr) - 1] \n", " yield big \n", " for i in range(len(arr) - 2, -1, -1):\n", " if arr[i] > big:\n", " big = arr[i]\n", " yield big" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[16, 17, 4, 3, 5, 2]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "arr = [16, 17, 4, 3, 5, 2]\n", "arr" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 5, 17]" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(getLeaders(arr))" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.2" } }, "nbformat": 4, "nbformat_minor": 2 }