-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #357 from hrishikeshSuresh/problem_121
added solution & modified README.md for problem 121
- Loading branch information
Showing
4 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
int maxcmp(int a, int b) { | ||
return (a >= b)? a : b; | ||
} | ||
|
||
/* max subarray problem by using Kadane's Algorithm | ||
*/ | ||
int maxProfit(int* prices, int pricesSize){ | ||
/* maxCur: current maximum | ||
* maxSoFar: found maximum for subarray so far | ||
*/ | ||
int maxCur = 0, maxSoFar = 0; | ||
for(int i = 1; i < pricesSize; i++) { | ||
maxCur = maxcmp(0, maxCur + prices[i] - prices[i - 1]); | ||
maxSoFar = maxcmp(maxSoFar, maxCur); | ||
} | ||
return maxSoFar; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
int findComplement(int num) { | ||
int TotalBits = 0; | ||
int temp = num; | ||
while(temp) { //To find position of MSB in given num. Since num is represented as a standard size in memory, we cannot rely on size | ||
//for that information. | ||
TotalBits++; //increment TotalBits till temp becomes 0 | ||
temp >>= 1; //shift temp right by 1 bit every iteration; temp loses 1 bit to underflow every iteration till it becomes 0 | ||
} | ||
int i, flipNumber = 1; //Eg: 1's complement of 101(binary) can be found as 101^111 (XOR with 111 flips all bits that are 1 to 0 and flips 0 to 1) | ||
for(i = 1; i < TotalBits; i++) { | ||
flipNumber += UINT32_C(1) << i; //Note the use of unsigned int to facilitate left shift more than 31 times, if needed | ||
} | ||
num = num^flipNumber; | ||
return num; | ||
} |