博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Best Time to Buy and Sell Stock III
阅读量:4549 次
发布时间:2019-06-08

本文共 1832 字,大约阅读时间需要 6 分钟。

Best Time to Buy and Sell Stock III

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

Design an algorithm to find the maximum profit. You may complete at most two transactions.

 

c++版本代码:

class Solution {public:    int maxProfit(vector
&prices) { int profit = 0, n = prices.size(); if( n==0 ) { return 0; } int l[n], r[n]; memset(l, 0, sizeof(int)*n); memset(r, 0, sizeof(int)*n); int min = prices[0]; for(int i=1; i
l[i-1] ? prices[i] - min : l[i-1]; min = prices[i] < min ? prices[i] : min; } int max = prices[n-1]; for(int i=n-2; i>=0; i--) { r[i] = max - prices[i] > r[i+1] ? max - prices[i] : r[i+1]; max = prices[i] > max ? prices[i] : max; } for (int i=0; i
profit ? l[i] + r[i] : profit; } return profit; }};

  Java版本代码:

public class Solution {    public int maxProfit(int[] prices) {     if(prices == null || prices.length == 0) {         return 0;     }     int n = prices.length;     int[] left = new int[n];     int[] right = new int[n];     int min = prices[0];     for(int i=1; i
prices[i] - min ? left[i - 1] : prices[i] - min; min = min < prices[i] ? min : prices[i]; } int max = prices[n-1]; for(int i=n-2; i>0; i--) { right[i] = right[i + 1] > max - prices[i] ? right[i + 1] : max - prices[i]; max = max > prices[i] ? max : prices[i]; } int profit = 0; for(int i=0; i
left[i] + right[i] ? profit : left[i] + right[i]; } return profit; }}

  

转载于:https://www.cnblogs.com/zlz-ling/p/4052873.html

你可能感兴趣的文章
个人博客作业Week1
查看>>
AsyncTask 学习笔记
查看>>
Light Oj 1005
查看>>
12、反射
查看>>
Redis中SAVE和BGSAVE的区别
查看>>
归德口有神龟石
查看>>
东风寒·杜甫
查看>>
韵语编年(之九:1983——1985)
查看>>
js声明变量作用域会提前
查看>>
委托详谈
查看>>
五容器
查看>>
【PMP】合同类型
查看>>
类命名空间和对象/实例命名空间
查看>>
脚本的含义
查看>>
BZOJ3669 NOI2014 魔法森林 LCT/最短路
查看>>
503. Next Greater Element II 下一个更大元素
查看>>
CSS3总结七:变换(transform)
查看>>
HTML基本标签2
查看>>
vscode编辑器常用快捷键
查看>>
解决idea server 控制台乱码问题
查看>>