首页 > 其他分享 >121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

时间:2022-11-19 22:45:53浏览次数:29  
标签:Sell Buy int max price 121 maxCur prices total

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0.

 class Solution {

   public int maxProfit(int[] prices) {        int maxCur = 0;        int total = 0;        for (int i = 1; i < prices.length; i++) {           if (total >= 0)              total += prices[i] - prices[i - 1];           else              total = prices[i] - prices[i - 1];                      maxCur = Math.max(maxCur, total);        }        return maxCur;    } }

标签:Sell,Buy,int,max,price,121,maxCur,prices,total
From: https://www.cnblogs.com/MarkLeeBYR/p/16907404.html

相关文章

  • UVa 12186 工人的请愿书
    详见紫书P444题目输入:员工数n百分比T员工1的直属上司员工2的直属上司...员工n的直属上司310000035000014600011222575757500输出......
  • 各类数据库写入Webhsell总结
    1.MySQL写入WebShell1.1写入条件数据库的当前用户为ROOT或拥有FILE权限;知道网站目录的绝对路径;PHP的GPC参数为off状态;MySQL中的secure_file_priv参数不能为NULL状态;......
  • xhsell下载,xshell免费下载、使用、无限期
    https://www.xshell.com/zh/free-for-home-school/  然后会发邮件过来  对应点击链接即可:(注意,有期限) ......
  • 121. 买卖股票的最佳时机 ----- 动态规划、历史最小一次遍历
    给定一个数组prices,它的第 i个元素 prices[i]表示一支给定股票第i天的价格。你只能选择某一天买入这只股票,并选择在未来的某一个不同的日子卖出该股票。设计......
  • 题解 UVA12265【贩卖土地 Selling Land】
    postedon2022-09-2414:33:29|under题解|sourceproblem一个黑白矩阵,求以每个点为右下角,能围出的周长最大的全白矩形的周长。\(n\leq2000\)。solution试图进行......
  • P1219 [USACO1.5]八皇后 Checker Challenge
    题目描述:把n个皇后无伤放进n*n的棋盘上。输出要求:按字典序输出前三个放置方案中第1~n行的皇后的列数构成的序列。 思路:核心难点在于如何记录前一个状态用于......
  • POJ 1952 BUY LOW, BUY LOWER
    DescriptionTheadviceto"buylow"ishalftheformulatosuccessinthebovinestockmarket.Tobeconsideredagreatinvestoryoumustalsofollowthi......
  • 第121期:一次成功的基于vue3和ts的CodeReview
    封面图CodeReview现场背景当前项目已经接入了公司自研的前端监控平台,已经有能力对线上运行的各个项目进行错误监控,并且可以统计相关报错信息及日志。对于报错问题的修复前段......
  • [COMP2121] Bertrand's Ballot Problem
    DescriptionSupposethereare$x$votesfor$A$and$y$notesfor$B$,and$x>y$.Howmanysequencesarethereofrevealingthevotessuchthatthenumbervote......
  • dijkstra 求最小环( CCPC桂林 - E. Buy and Delete )
    原文题意经过转化后,本质就是求最小环。有向图有以下三种实现方式,而无向图只能用第一种实现方式。实现方式1:删边求最短距离有向图实现方式2:回到起点构成环有向图实现......